【发布时间】:2017-09-09 22:33:46
【问题描述】:
我将一个文件夹中的所有 CSV 文件合并到一个 Excel 工作表中。
Sub MergeFiles_Click()
Dim strSourcePath As String
Dim strDestPath As String
Dim strFile As String
Dim strData As String
Dim x As Variant
Dim Cnt As Long
Dim r As Long
Dim c As Long
Application.ScreenUpdating = False
strSourcePath = Sheet1.Range("G2").Value
If Right(strSourcePath, 1) <> "\" Then strSourcePath = strSourcePath & "\"
strFile = Dir(strSourcePath & "*.csv")
Do While Len(strFile) > 0
Cnt = Cnt + 1
If Cnt = 1 Then
r = 6
Else
r = Cells(Rows.Count, "A").End(xlUp).Row + 1
End If
Open strSourcePath & strFile For Input As #1
Do Until EOF(1)
Line Input #1, strData
x = Split(strData, ",")
For c = 0 To UBound(x)
Cells(r, c + 1).Value = Trim(x(c))
Next c
r = r + 1
Loop
Close #1
strFile = Dir
Loop
Application.ScreenUpdating = True
If Cnt = 0 Then _
MsgBox "No CSV files were found...", vbExclamation
End Sub
这会将所有 CSV 文件合并到一张纸上,但每个 CSV 文件在顶部都有一个标题和其他信息,占 12 行。
我想为第一个 CSV 保留 12 行,但在放入 Excel 工作表之前将它们从其余文件中删除。
我希望文件显示为一个,而不是看起来像是文件被复制并粘贴到工作表上。
【问题讨论】:
-
您知道您正在使用的数据,但请注意 CSV 格式通常允许将逗号嵌入文字字符串(用双引号括起来的字段“like this”)。如果你得到其中任何一个,你的代码就会失败。
-
@RichHolton 所以在测试后我发现了一些导致问题的实例。我该怎么做才能避免这个问题?
-
您可能会发现这个问题/答案很有帮助:stackoverflow.com/questions/12197274/…
-
@RichHolton 我浏览了那篇文章并抓取了使用 QueryTables 导入 csv 的代码并对其进行了测试,导入一个文件可以正常工作。我该如何重新安排它以继续并抓取文件夹中的每个 csv 以实现我想要做的事情?