【问题标题】:Importing multiple CSV files and add filename and row导入多个 CSV 文件并添加文件名和行
【发布时间】:2018-01-29 23:19:30
【问题描述】:

我有一个包含多个 csv 文件的目录,我希望将数据添加到表中,但也要引用 csv 文件和行

例如,如果我有 2 个 csv 文件

csv1

year;price
2016;£50
2017;£40

csv2

year;price
2016;£20
2017;£10

我希望表格如下所示:

File | Row | Year | Price
-------------------------
csv1 | 1   | 2016 | £50
csv1 | 2   | 2017 | £40
csv2 | 1   | 2016 | £20
csv2 | 2   | 2017 | £10

到目前为止,我可以添加数据,但我正在努力添加文件名和行,有什么想法吗?

这是我目前所拥有的

Sub Update_Data()
    '~>Define variables
    Dim fPath   As String:      fPath = "C:\Archive\"
    Dim csvFileName    As String

    '~>Start the CSV file listing
    csvFileName = Dir(fPath & "*.csv")

    Do While Len(csvFileName) > 0
        '~>Retrieve the data from the .csv file
        Call Append_CSV_Data(csvFileName)

        '~>Ready next CSV
        csvFileName = Dir
    Loop

End Sub

Sub Append_CSV_Data(csvFileName)
    Dim destCell As Range
    Dim qTable As QueryTable
    Dim wSheet As Worksheet

    Set destCell = ActiveSheet.Cells(Rows.Count, "C").End(xlUp).Offset(1)

    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;" & csvFileName, Destination:=destCell)
        .TextFileStartRow = 2
        .TextFileParseType = xlDelimited
        .TextFileSemicolonDelimiter = True
        .Refresh BackgroundQuery:=False
    End With

    For Each wSheet In ThisWorkbook.Worksheets
        For Each qTable In wSheet.QueryTables
            qTable.Delete
        Next qTable
    Next wSheet
End Sub

【问题讨论】:

  • 您想遍历所有可用的 .csv 文件吗?
  • 是的,但是上面的代码已经做到了。我正在努力添加文件名和行

标签: vba excel csv


【解决方案1】:

可能会添加一些代码

'get new last row
lastCell = ActiveSheet.Cells(Rows.Count, "C").End(xlUp).Offset(1)
'Input file name
Range(Cells(destCell.Row, 1), Cells(lastCell , 1)) = csvFileName
'input row
For i = 1 to lastCell - destCell.Row 
  Cells(destCell.Row + i - 1, 2) = i
Next i

在你引入查询表之后,但在你结束子之前把它。

【讨论】:

  • 我用msgbox csvFileName 替换了Call Append_CSV_Data(csvFileName),它只是文件名,而不是踢出的路径。你的代码不能只用文件名做任何事情,它也需要位置。
  • 我的代码正在运行并生成一个没有文件名和行列的表格,添加您的建议也是如此
  • 就是这样,你必须在我没有意识到的情况下进行编辑。感谢您的坚持
  • 我修复了它,可能是我的错误,我不得不将 destCell 添加到循环中,因为 t 从未重置
  • 感谢您的帮助,非常感谢...我也不知道这里有聊天哈哈
猜你喜欢
  • 2017-04-13
  • 1970-01-01
  • 2020-08-31
  • 2017-04-21
  • 1970-01-01
  • 2012-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多