为什么第一次input在Visual Basic命令中跳过一行来将文本文件编译到Excel中?

我的代码的意图是将许多文本文件编译成一个Excel电子表格。 我能够检索数据,但第一个命令,以获得“性别”开始在Excel电子表格的第二行; 而后续的命令(例如,获得“名字”)正确地开始填充在第一行。 任何想法如何在第1行开始“性别”?

Sub read_text() Set wb = Workbooks.Add workingflnm = ActiveWorkbook.Name i = 1 'First row Set fd = CreateObject("Scripting.Filesystemobject") pthnm = "C:\TestFolder" Set fs = fd.GetFolder(pthnm) For Each fl In fs.Files If InStr(1, fl.Name, "txt", vbTextCompare) > 0 Then Set Txtobj = CreateObject("Scripting.filesystemobject") Set Txtfl = Txtobj.getfile(fl) Set Txtstrm = Txtfl.openastextstream(1, -2) Do While Txtstrm.atendofstream <> True rdln = Txtstrm.readline If InStr(1, rdln, "ender: ", vbTextCompare) > 1 Then 'This if/then looks for the "gender" value in each text file x1 = InStr(1, rdln, "ender: ", vbTextCompare) strg = Left(rdln, 40) Workbooks(workingflnm).Sheets(1).Cells(i, 1) = strg 'i = i + 1 End If If InStr(1, rdln, "irst Name: ", vbTextCompare) > 1 Then 'This if/then looks for the "first name" value in each text file x1 = InStr(1, rdln, "irst Name: ", vbTextCompare) strg = Left(rdln, 40) Workbooks(workingflnm).Sheets(1).Cells(i, 2) = strg 'i = i + 1 End If If InStr(1, rdln, "ast Name: ", vbTextCompare) > 1 Then 'This if/then looks for the "last name" value in each text file x1 = InStr(1, rdln, "ast Name: ", vbTextCompare) strg = Mid(rdln, x1 + Len("ast Name: "), x2 + 50 - (x1 + Len("ast Name: "))) Workbooks(workingflnm).Sheets(1).Cells(i, 3) = strg i = i + 1 End If Loop End If Next End Sub 

每个文本文件的内容如下所示:

 Contact Information Name: Smith, John Home Phone: 6465551234 Street Address: 1313 Mockingbird Work Phone: Apt or Unit: Fax: City/State/Zip: YONKERS,NY,10701 Email: john@john.john County: Westchester Contact Time: Respond Time: -------------------------------------------------------------------------------------------------------------------------- User Info First Name: John Last Name: Smith Date of Birth: 11/7/1957 Gender: Male 

我认为你的方法是根本上有缺陷的。 因为你在错误的时间递增i 因为i是在每一条数据之间共享的,所以每当你增加i就会在下一行。

我的build议:改用ReadAll 。 你的数据应该有一个分隔符,以便你可以parsing每条logging,并确定你有相同的logging相同的行。 如果没有分隔符,你怎么知道要创新纪录呢?

这会使你的代码如下所示:

 dim currentRow as integer, i as integer, j as integer dim data as string currentRow = 1 'for each file you'll need to set up this loop data = Txtstrm.ReadAll records = Split(records, "YOURDELIMETER HERE") For i = LBound(records) To UBound(records) lines = Split(records, vbNewLine) For j = LBound(lines) To UBound(lines) rdln = lines(j) If InStr(1, rdln, "ender: ", vbTextCompare) > 1 Then 'This if/then looks for the "gender" value in each text file x1 = InStr(1, rdln, "ender: ", vbTextCompare) strg = Left(rdln, 40) Workbooks(workingflnm).Sheets(1).Cells(i + 1, 1) = strg 'Do not increment i manually as that is handled by for loop End If ' etc... Next Next currentRow = currentRow + i 'next file