我想在TXT文件中使用关键字进行搜索,并将找到关键字的行写入excel单元格。
我有一段可行的VBA代码,但它只写了关键字+我给它的额外字符。 因此,我必须知道关键字后面有多少个字符。
我的问题是有人可以帮助我编写完整的代码代码..所以到了行尾......
我需要:
谢谢!
Private Sub CommandButton1_Click()
Dim myFile As String
Dim text As String
Dim textLine As String
Dim S_Name As Integer
myFile = Application.GetOpenFilename()
Open myFile For Input As #1
Do Until EOF(1)
Line Input #1, textLine
text = text & textLine
Loop
Close #1
S_Name = InStr(text, "keyword1")
Range("A10").Value = Mid(textLine, S_Name + 0, 30)
'save sheet to txt file
ActiveWorkbook.SaveAs Filename:="c:" & "keyword_file " + Format(Now(), "YYYYMMDD") _
& ".txt", FileFormat:=xlTextWindows
End Sub
答案 0 :(得分:1)
循环遍历每一行时,测试关键字的行,并仅为变量text
分配符合条件的行,然后立即退出循环...
Open myFile For Input As #1
text = ""
Do Until EOF(1)
Line Input #1, textLine
If InStr(1, textLine, "keyword1") > 0 Then
text = textLine
Exit Do
End If
Loop
Close #1
Range("A10").Value = text
当换行符(chr(10
)或vbLf
)用于标记行的结尾时,可以使用FileSystemObject代替...
'
'
'
Dim oFSO As Object
Dim oTS As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oTS = oFSO.OpenTextFile(myFile)
text = ""
Do Until oTS.AtEndOfStream
textLine = oTS.ReadLine
If InStr(1, textLine, "keyword1") > 0 Then
text = textLine
Exit Do
End If
Loop
oTS.Close
Range("A10").Value = text
'etc
'
'
Set oFSO = Nothing
Set oTS = Nothing