如何将两个不同的CSV文件转换为同一Excel工作簿中的两个工作表?

时间:2019-03-31 06:57:42

标签: excel csv vbscript wincc

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

这是我的代码:

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    

1 个答案:

答案 0 :(得分:0)

您实际上不需要使用TextToColumns。对于第一个CSV文件,该工作表已经存在;对于第二个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