繁体   English   中英

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

[英]How to find specific text in text file, and add additional text in the following line in 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 文件的方法。 有什么想法、建议吗?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM