0

我有一个将 csv 数据复制到 excel 表的解决方案,但它仅适用于 1 个 CSV 文件到 1 个 Excel 表。如何将多个 CSV 文件传输到 Excel 中的多个工作表?

这是我的代码:

Dim oExcel  
Set oExcel = CreateObject("Excel.Application")  
With oExcel  
    .DefaultSaveFormat=51  
    .Workbooks.Open sourceFile  
    .Sheets(1).Columns("A").TextToColumns .Range("A1"), , , , , True  
    .Sheets.add
    .ActiveWorkbook.SaveAs outputFile, 51  
    .Quit  
End With    
4

1 回答 1

0

您实际上不需要使用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
于 2019-04-01T02:04:39.283 回答