想知道您是否可以幫助解決VBA問題。我拼湊不真正知道我在做什麼如下:使用VBA將數據從.csv導入excel文檔
Sub Import_Raw_Stripe_data()
Dim fileDialog As fileDialog
Dim strPathFile As String
Dim strFileName As String
Dim strPath As String
Dim dialogTitle As String
Dim Tworkbook As Workbook
Dim Sworkbook As Workbook
dialogueTitle = "Select File to Import"
Set fileDialogue = Application.fileDialog(msoFileDialogFilePicker)
With fileDialogue
.InitialFileName = "L:\Downloads"
.AllowMultiSelect = False
.Filters.Clear
.Title = dialogueTitle
If .Show = False Then
MsgBox "No file selected."
Exit Sub
End If
strPathFile = .SelectedItems(1)
End With
Set Sworkbook = Workbooks.Open(fileName:=strPathFile)
Set Tworkbook = ThisWorkbook
End Sub
其中,據我可以告訴打開Excel中的一個文件對話框,允許用戶選擇一個文件,然後打開它。
我想這樣做的是以下幾點:
1)打開文件對話框,選擇一個.csv文件導入從(完成)成.XLSM主文件(多表)?
2)從.csv中選擇某些列(在這種情況下,列A,Q,R和S),複製它們並將它們導入名爲「Raw Stripe Data」的主excel文件的第二個表格中。
任何有關此事的幫助將不勝感激。
更新:我設法找到下面的代碼:
Sub load_csv()
Dim fStr As String
With Application.fileDialog(msoFileDialogFilePicker)
.Show
If .SelectedItems.Count = 0 Then
MsgBox "Cancel Selected"
Exit Sub
End If
'fStr is the file path and name of the file you selected.
fStr = .SelectedItems(1)
End With
With ThisWorkbook.Sheets("Stripe Raw Data").QueryTables.Add(Connection:= _
"TEXT;" & fStr, Destination:=ThisWorkbook.Sheets("Stripe Raw Data").Range("$A$1"))
.Name = "CAPTURE"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
ActiveWorkbook.Save
End With
End Sub
這個偉大的工程 - 但反正是有有它不會覆蓋已經導入的數據? (例如,如果我使用它兩次,第二次導入覆蓋第一次)。
是的,我明白這是需要發生的,但問題是,我不知道如何實現它。我會假設需要有某種循環,但是再一次,我的第二天使用VBA。 – Spnkmyr
如果您擴展程序以將'ThisWorkbook.Sheets(「Stripe Raw Data」)。Range(「$ A $ 1」)'作爲參數如下:'load_csv(rng As Range)' - 那麼您可以更改導入對於這個:ThisWorkbook.Sheets(「Stripe Raw Data」)。QueryTables.Add(Connection:= _ 「TEXT;」&fStr,Destination:= rng)' - 現在您可以反覆調用'load_csv()'參數。 – Leviathan
嘿,謝謝你的幫助。在你的例子中,你能詳細說明實現這個過程所需要的步驟(特別是load_csv(rng作爲範圍)嗎?你可以聲明Worksheet.Range = rng然後調用rng(「$ B $ 1」)或類似的東西嗎?這與數據導入的位置有關,我基本上希望每個數據集都要加載到最後一個數據集(而不是相同的單元格,這會將所有先前的數據橫向推送)如果您說Destination:= rng,那麼您如何指定初始值範圍,然後是後續的進口範圍? – Spnkmyr