Excel – 在TXT文件中search关键字,并将find关键字的行写入excel单元格
我想用TXT文件中的关键字进行search,并将find关键字的行写入Excel单元格。
我有一个VBA代码的作品,但它只写入关键字+我给额外的字符。 所以我很快就必须知道关键字后有多less个字符。
我的问题是,有人可以帮助我的代码,它可以写完整的行..所以结束行..
我需要:
- function打开文件
- 轻松添加关键字
- 轻松添加关键字放置的单元格
谢谢!!
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
在循环每一行时,testing关键字的行,并只将variablestext
分配符合条件的行,然后立即退出循环…
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