如何检测文本文件(EOF)在VBScript的结束?

我正在使用VBscript将文本文件中的信息sorting到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输出

有人可以帮我弄清楚如何到文本文件的末尾?

正如我在评论中提到的,你的问题与你的variables有关,因为你正试图重复使用它们,但是没有做好。 如果你手动进入你的代码,你会看到,在第一次迭代中,你将arrFileLines(0)添加到arrFileLines(0) ,然后将arrFileLines(0)存储到text
但是,然后你走在你的内部For循环,并迭代i ,这将分裂后离开For循环4

第二次进入你的循环时,你将把arrFileLines(4)添加到arrFileLines(4) ,然后将arrFileLines(1) (它是空的)存储到text 。 你不会得到任何错误,因为数组有固定的尺寸,并将在范围内,直到完成你的文件,但你也不会得到任何结果。
这就是为什么我build议你使用不同的variables,并避免重复使用。
实际上,如果唯一的目的是将CSV中的值添加到Excel工作表中,您甚至不需要将objFile.ReadLine存储到arrFileLines因为您没有使用该数组。 只需将其直接添加到Text

所以,通过一些修改,比如variables重命名等等,你最终会得到如下的结果:

 ' The rest of your code, Variables declarations and so forth iRow = 2 ' Starting Row iCol = 1 ' Starting Col Do While Not objFile.AtEndOfStream currLine = objFile.ReadLine arrLine = Split(currLine, ";") For Each item In arrLine objSheet.Cells(iRow, iCol).Value = item iCol = iCol + 1 Next iCol = 1 ' Reset for every row iRow = iRow + 1 Loop ' The rest of your code