如何在文本文件中查找特定文本,并在excel VBA的以下行中添加其他文本

我需要打开一个txt文件,找到一个特定的字符串,在其下方写几行,保存生成的文件并关闭它。这是我到目前为止的内容:

Sub EditMyTXT()

Dim FileNum As Integer
Dim DataLine As String

FileNum = FreeFile()
Open "E:\Host.txt" For Input As #FileNum

While Not EOF(FileNum)
    Line Input #FileNum,DataLine
        If DataLine = "TextToFind" Then
             move to the next line
             write text "TextToWriteBelow TextToFind"
             move to the next line
             write text "MoreTextToWriteBelow"
        Else: End If
Wend

 Save FileNum
 Close FileNum

End Sub

我找不到以允许我读取写入内容的方式打开txt文件的方法。有任何想法,建议吗?

charlesluo326 回答:如何在文本文件中查找特定文本,并在excel VBA的以下行中添加其他文本

您还可以将文本文件读入字符串变量,进行更改并像这样写回

Sub EditMyTXT_Full()

    Dim FileNum As Integer
    Dim DataLine As String
    Dim fileName As String

    fileName = "D:\TEMP\HOST.TXT"

    FileNum = FreeFile()
    Open fileName For Input As #FileNum

    Dim textData As String
    ' read the complete file into textdata
    textData = Input$(LOF(FileNum),FileNum)
    Close #FileNum

    Dim searchLine As String
    Dim newLines As String

    searchLine = "Test"
    newLines = "New Line 1" & vbCrLf & "New Line 2"

    Dim vdat As Variant
    vdat = Split(textData,vbCrLf)

    Dim i As Long
    ' This is the loop through the lines but completely in memory
    For i = LBound(vdat) To UBound(vdat)
        If vdat(i) = searchLine Then
            vdat(i) = vdat(i) & vbCrLf & newLines
        End If
    Next i

    textData = Join(vdat,vbCrLf)

    FileNum = FreeFile()
    Open fileName For Binary Access Write As #FileNum
    ' write the text back in one step
    Put #FileNum,textData
    Close #FileNum

End Sub
本文链接:https://www.f2er.com/3164377.html

大家都在问