您实际上不需要使用TextToColumns
. 对于第一个 CSV 文件,工作表已经存在,对于第二个,您可以将文件作为另一个工作簿打开,然后使用该Worksheet.Copy
方法在第一个工作表之后复制工作表。
你去:
Const xlWorkbookDefault = 51
Dim sourceFile1, sourceFile2, outputFile
Dim xlApp, xlWorkbook1, xlWorkbook2
sourceFile1 = "...\CSV1.csv"
sourceFile2 = "...\CSV2.csv"
outputFile = "...\output.xlsx"
Set xlApp = CreateObject("Excel.Application")
With xlApp
Set xlWorkbook1 = .Workbooks.Open(sourceFile1)
Set xlWorkbook2 = .Workbooks.Open(sourceFile2)
xlWorkbook2.Sheets(1).Copy , xlWorkbook1.Sheets(1)
xlWorkbook2.Close
.xlWorkbook1.SaveAs outputFile, xlWorkbookDefault
.Quit
End With
为了使其更通用,您可以调整之前的代码以处理任意数量的 CSV 文件:
Const xlWorkbookDefault = 51
Dim sourceFiles(5)
Dim outputFile
Dim xlApp, xlWorkbook1, xlWorkbook2
sourceFiles(0) = "...\CSV1.csv"
sourceFiles(1) = "...\CSV2.csv"
sourceFiles(2) = '...
' TODO: Add more files.
outputFile = "...\output.xlsx"
Set xlApp = CreateObject("Excel.Application")
With xlApp
Set xlWorkbook1 = .Workbooks.Open(sourceFiles(0))
For i = 1 To UBound(sourceFiles)
Set xlWorkbook2 = .Workbooks.Open(sourceFiles(i))
xlWorkbook2.Sheets(1).Copy , xlWorkbook1.Sheets(i)
xlWorkbook2.Close
Next
.xlWorkbook1.SaveAs outputFile, xlWorkbookDefault
.Quit
End With