我试图读取以分号分隔的CSV文件,并将其数据逐个单元地写入Excel文件。
我的CSV数据如下:
CATALOG;NAME ;TYPE ---;---;--- test ;Mapping ;BASE test ;RECEPIENT ;BASE
我正在尝试使用下面的VBScript代码将此数据附加到Excel。
Set objShell = WScript.CreateObject ("WScript.Shell")
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open(objShell.CurrentDirectory & "\" & "Data.xlsx")
'objExcel.Application.Visible = True
Set objSheet = objExcel.ActiveWorkbook.Worksheets(1)
LastRow = objSheet.UsedRange.Rows.Count
WScript.Echo "LastRow "&LastRow
'objExcel.Cells(LastRow+1, 1).Value = "Test value"
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile(objShell.CurrentDirectory & "\" & "Output.csv",1)
Dim strLine
Do While Not objFileToRead.AtEndOfStream
strResults = objFileToRead.ReadAll
Loop
objFileToRead.Close
Set objFileToRead = Nothing
If Trim(strResults) <> "" Then
' Create an Array of the Text File
arrline = Split(strResults, vbNewLine)
'WScript.Echo UBound(arrline)
End If
For i = 0 To UBound(arrline)
Do
If i = 1 Then Exit Do
If arrline(i) = "" Then
' checks for a blank line at the end of stream
Exit For
End If
ReDim Preserve arrdata(i)
arrdata(i) = Split(arrline(i), ";")
For j = 0 To UBound(arrdata(i))
WScript.Echo Trim(arrdata(i)(j))
'objExcel.Cells(LastRow+1+i,j).Value = Trim(arrdata(i)(j))
Next
Loop While False
Next
objExcel.ActiveWorkbook.Save
objExcel.ActiveWorkbook.Close
objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit
它显示的是csv数据,但会引发错误
Execl.vbs(41,6)Microsoft VBScript运行时错误:未知的运行时错误
第41行是
objExcel.Cells(LastRow+1+i,j).Value = Trim(arrdata(i)(j))
如果我将一些硬编码的值(5,6 ..)替换为j
,则可以使用它,但是它不能将j
用作变量。我无法输入j
的任何值,因为输入CSV中的列数未知。请让我知道我在哪里犯错以及如何解决。
答案 0 :(得分:1)
我敢打赌,问题在于从索引不正确的列0开始循环遍历这些列。请尝试调整此行:
For j = 0 To UBound(arrdata(i))
成为
For j = 1 To UBound(arrdata(i))
并确保验证它不会忽略最左边一栏中的真实数据!