【发布时间】:2017-02-04 02:06:24
【问题描述】:
我正在使用 VBscript 将文本文件中的信息排序到 Excel 工作表中。我可以这样做,但是只读取了一行文本,并且循环控制似乎没有转到文本文件的下一行。我为此使用 AtEndOfStream,但正如我所说,我只得到一行输出。谁能帮我弄清楚如何执行程序直到文件结束?
代码如下:
Set objExcel = CreateObject("Excel.Application") 'Bind to the Excel object
objExcel.Workbooks.Add 'Create a new workbook.
Sheet = 1 'Select the first sheet
Set objSheet = objExcel.ActiveWorkbook.Worksheets(Sheet) 'Bind to worksheet.
objSheet.Name = "ErrorSpreadsheet" 'Name the worksheet
strExcelPath = "c:\scripts\ErrorSpreadsheet.xlsx" 'Set the save location
objSheet.Range("A1:E1").Font.Bold = True
objExcel.Columns(5).AutoFit()
objSheet.Cells(1, 1).Value = "Date" 'Row 1 Column 1 (A)
objSheet.Cells(1, 2).Value = "Time" 'Row 1 Column 2 (B)
objSheet.Cells(1, 3).Value = "Category" 'Row 1 Column 3 (C)
objSheet.Cells(1, 4).Value = "Error" 'Row 1 Column 4 (D)
objSheet.Cells(1, 5).Value = "Index" 'Row 1 Column 5 (E)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("c:\scripts\ErrorMsg.txt",1)
i = 0
r = 2
c = 1
j = 0
Do While NOT objFile.AtEndOfStream
Redim Preserve arrFileLines(10)
arrFileLines(i) = objFile.ReadLine
text = arrFileLines(j)
'Dim a()
a = Split(text,";")
For Each line In a
objSheet.Cells(r,c).Value = a(i)
i = i + 1
c = c + 1
Next
j = j + 1
r = r + 1
Loop
objFile.Close
objExcel.ActiveWorkbook.SaveAs strExcelPath
objExcel.ActiveWorkbook.Close
objExcel.Application.Quit
我现在以没有任何错误的方式编写代码。在我的 excel 文件中,我既有标题行也有拆分文本文件的一行,但没有以下任何行。文本文件是这样写的:
9/23;12:00;cat;error;236
9/24;12:30;cat2;error;897
9/24;4:06;cat5;error;23
9/25;3:45;cat1;error;54
9/26;1:09;cat6;error;18
所以我在 excel 中得到的输出是 Excel Output
谁能帮我弄清楚如何到达文本文件的末尾?
【问题讨论】:
-
您确实注意到,由于您正在重用
i,因此您将第一行添加到arrFileLines(0),但第二次您应该将该行添加到您的arrFileLines(i),您将将它添加到arrFileLines(4) because of the iteration in theFor`循环,对吗?另外,您在arrFileLines(i)中添加该行,但随后从arrFileLines(j)读取,这可能会导致无法预料的问题。我会为arrFileLines使用i(或另一个更好命名的变量),为a使用j(或另一个更好命名的变量),并避免重复使用这样的变量 -
另外,你在循环中的
Redim Preserve arrFileLines(10)是没用的。对于每次迭代,您都重新声明arrFileLines,维度为 10,但保留现有数据。您可以在没有Preserve的循环之前声明它,也可以动态地使用它,使用ReDim arrFileLines(-1) before the loop and then, inside the loop you doReDim Preserve arrFileLines(UBound(arrFileLines)+1)` 来获得一个具有适当尺寸的数组 -
@VictorMoraes 感谢您的回复,但如果我尝试将 arrFileLines(i) = objFile.ReadLine 更改为 arrFileLines(j) = objFile.ReadLine,则会收到错误消息“下标超出范围:'i'" 在 objSheet.Cells(r,c).Value = a(i) 行中。我该如何解决这个问题?
-
请看下面我的回答