在 Excel 中将数据从外部 CSV 追加到表中



如果我有一个 excel 文件中包含数据的表,如何使用"获取外部数据 - 从 csv"将数据附加到该表中。我的表最后一个单元格在 A3016 中,然后我突出显示了 A3017 单元格,然后从该单元格中选择"获取外部数据",数据被导入,但它不属于表格,就像我手动将数据添加到下一个空闲单元格一样。

您可以尝试添加此VBA代码以达到预期的结果:

Sub Append_CSV_File()
    Dim csvFileName As Variant
    Dim destCell As Range
    Set destCell = Worksheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Offset(1)      'CHANGE SHEET NAME
    csvFileName = Application.GetOpenFilename(FileFilter:="CSV Files (*.csv),*.csv", Title:="Select a CSV File", MultiSelect:=False)
    If csvFileName = False Then Exit Sub
    With destCell.Parent.QueryTables.Add(Connection:="TEXT;" & csvFileName, Destination:=destCell)
        .TextFileStartRow = 2
        .TextFileParseType = xlDelimited
        .TextFileCommaDelimiter = True
        .Refresh BackgroundQuery:=False
    End With
    destCell.Parent.QueryTables(1).Delete
    End Sub

让我知道这是否适合您。

最新更新