【发布时间】: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 文件吗?
-
是的,但是上面的代码已经做到了。我正在努力添加文件名和行