将CSV文件导入Excel

10

我想请你帮我处理以下事项:

我有从软件应用程序导出的CSV文件,需要将其导入Excel以分析数据。每天会生成40-50个CSV文件。目前我通过“从文本获取外部数据”手动完成此操作。导入期间记录的代码如下:

With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;SYSTEM:Users:catalin:Documents:LINELLA:WH Analytics:data:pick 01-18:050:Inquiry closed lists  SKU_0142.csv" _
    , Destination:=Range("A1704"))
    .Name = "Inquiry closed lists  SKU_0142"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .RefreshOnFileOpen = False
    .BackgroundQuery = True
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = xlMacintosh
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = True
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = False
    .TextFileOtherDelimiter = ";"
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
    .Refresh BackgroundQuery:=False
    .UseListObject = False
End With
Selection.End(xlDown).Select
Range("A1710").Select

我希望能够自动导入所选文件夹中的所有CSV文件,当我放置新文件并启动导入过程时。 每个文件都应立即插入到上一个文件的最后一行。

非常感谢您的帮助。


也许这个插件会有用?你仍然需要手动选择最后一行(CTRL+向下箭头),但其他部分将自动完成。 - nixda
1个回答

9

将你记录的代码放入一个函数中,用变量替换静态文件名,然后为文件夹中的每个*.csv文件调用该函数。要使下面的示例工作,您需要在与csv文件相同的文件夹中保存带有此宏的文件。对于我的快速测试,我不得不将分隔符从;更改为,,并删除最后一行.UseListObject = False

Sub ImportAllCSV()
  Dim FName As Variant, R As Long
  R = 1
  FName = Dir("*.csv")
  Do While FName <> ""
    ImportCsvFile FName, ActiveSheet.Cells(R, 1)
    R = ActiveSheet.UsedRange.Rows.Count + 1
    FName = Dir
  Loop
End Sub

Sub ImportCsvFile(FileName As Variant, Position As Range)
  With ActiveSheet.QueryTables.Add(Connection:= _
      "TEXT;" & FileName _
      , Destination:=Position)
      .Name = Replace(FileName, ".csv", "")
      .FieldNames = True
      .RowNumbers = False
      .FillAdjacentFormulas = False
      .RefreshOnFileOpen = False
      .BackgroundQuery = True
      .RefreshStyle = xlInsertDeleteCells
      .SavePassword = False
      .SaveData = True
      .AdjustColumnWidth = True
      .TextFilePromptOnRefresh = False
      .TextFilePlatform = xlMacintosh
      .TextFileStartRow = 1
      .TextFileParseType = xlDelimited
      .TextFileTextQualifier = xlTextQualifierDoubleQuote
      .TextFileConsecutiveDelimiter = False
      .TextFileTabDelimiter = True
      .TextFileSemicolonDelimiter = False
      .TextFileCommaDelimiter = False
      .TextFileSpaceDelimiter = False
      .TextFileOtherDelimiter = ","
      .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
      .Refresh BackgroundQuery:=False
  End With
End Sub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接