我想逐行读取文本文件(使用 readline 函数而不是 readall)以在文本文件中搜索重复的字符串(如“嗨,你好吗?”)。用户提供字符串和文本文件路径作为输入。我希望将以下输出填充到输出 excel 中:1. 测试数据(您在文本文件中搜索的字符串并且多次出现)2.内容每行应填充在第 3 列中。如果在任何行中找到测试数据,则在输出 excel 文件的另一列中导致“Y”否则为“N” 4.行索引(意味着,对于第一行它将是 1,依此类推)。
我已经在网上搜索并相应地制作了我的代码,但我无法在整个文本文件中循环读取行功能,我无法在结果输出 excel 中生成每一行的内容。如果你能帮助我,我将非常感激在代码中。
Sub main()
'creating new excel file in date-time format for gathering output
Dim a
a = Now
Dim strFileName
a = Replace(a, "/", "_")
a = Replace(a, ":", "_")
a = Replace(a, " ", "_")
strFileName = "search output_" & a & ".xls"
Set objExcel = CreateObject("Excel.Application")
'objExcel.Visible = True
Set objWorkBook = objExcel.Workbooks.Add()
Set Objsheet = objWorkBook.Sheets(1)
Row = 4
Objsheet.Cells(Row, 2) = "Test data"
Objsheet.Cells(Row, 4) = "Total row count"
Objsheet.Cells(Row, 6) = "Each row Index"
Objsheet.Cells(Row, 8) = "Row content"
Objsheet.Cells(Row, 10) = "Test data found ?" & vbNewLine & "Y" & "or" & "N"
Objsheet.Cells(Row, 12) = "Count of test data in the row"
Objsheet.Cells(Row, 14) = "Reported by"
Dim Str_input, strTextFile 'declaring variables
Str_input = Trim(TextBox_String.Text) 'user providing input search string
strTextFile = TextBox_Path.Text 'User providing text file path
Const ForReading = 1
'contents = ObjFile.readall
'contents = ObjFile.ReadLine
'i = 0
'linesArray = Split(contents, Chr(10))
'For Each lineStr In linesArray
'If InStr(lineStr, Str_input) Then
'i = i + 1
'End If
'Next
'ObjFile.Close
Set ObjFso = CreateObject("Scripting.FileSystemObject")
Set ObjFile = ObjFso.OpenTextFile(strTextFile, ForReading)
Content = ObjFile.Readall
Do While Not ObjFile.AtEndOfStream
contents = ObjFile.ReadLine
MsgBox "the output" & Content
Loop
'Set fso = CreateObject("Scripting.FileSystemObject")
'Set listFile = fso.OpenTextFile(aniLines).Readall
'Do While Not listFile.AtEndOfStream
'fName = listFile.ReadLine()
'WScript.Echo fName
'Loop
'Next
Row = 6
Objsheet.Cells(Row, 2) = Str_input
Objsheet.Cells(Row, 4) = ObjFile.Line - 1 'No of rows in total
Objsheet.Cells(Row, 6) = " Each row index"
Objsheet.Cells(Row, 8) = "Row content"
Objsheet.Cells(Row, 10) = "Test data found ?" & "Y" & "or" & "N"
Objsheet.Cells(Row, 12) = "Count of test data in the row"
Objsheet.Cells(Row, 14) = "Alex Rider"
objWorkBook.SaveAs "D:\" & strFileName 'saving the output excel
Set objExcel = Nothing: Set objBook = Nothing: Set Objsheet = Nothing
End Sub