将多个CSV文件导入主Excel Excel电子表格,并将数据附加到以前的导入

时间:2016-02-18 09:01:53

标签: excel vba excel-vba csv

我有一个脚本可以将.csv文件导入工作表"数据"

首次导入后,所有后续导入将显示在先前导入的右侧,而不会添加到底部(最后一行)。

我认为问题涉及脚本的这个区域:     目的地:= ThisWorkbook.Sheets("数据")范围(" $ A $ 1&#34))

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("Data").QueryTables.Add(Connection:= _
    "TEXT;" & fStr, Destination:=ThisWorkbook.Sheets("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

    End With
End Sub

1 个答案:

答案 0 :(得分:0)

您需要检查目的地以查看下一个未使用的单元格是什么。

With ThisWorkbook.Sheets("Data")
    .QueryTables.Add(Connection:= _
  ..., Destination:=.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
'lots of other stuff
End With

您可以反复重新引用ThisWorkbook.Sheets(" Data"),但使用With ... End With statement会更容易。