【问题标题】:How to find specific text in text file, and add additional text in the following line in excel VBA如何在文本文件中查找特定文本,并在 excel VBA 的以下行中添加附加文本
【发布时间】:2020-03-01 03:00:13
【问题描述】:

我需要打开一个 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 文件的方法。有什么想法、建议吗?

【问题讨论】:

  • 打开一个新文件进行输出并将内容复制到该新文件中,根据需要添加新内容。
  • 从家里开车时,我也有同样的想法。我将在明天实施并重新发布。谢谢

标签: excel vba text replace


【解决方案1】:

你也可以将文本文件读入一个字符串变量,改变它然后再写回去

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

【讨论】:

  • 太棒了,它完成了工作!
  • 如何修改代码如“newLines”插入到“vdat(i) = searchLine”下面的第二行,保留第i+1行的内容。像这样:
  • 您可能需要将 for 循环修改为类似 v1Dat(i + 1) = v1Dat(i + 1) & vbCrLf & newLines 的内容。并且不要忘记事先Redim 数组,如ReDim Preserve v1Dat(UBound(v1Dat) + 1)
猜你喜欢
  • 2014-05-02
  • 1970-01-01
  • 1970-01-01
  • 2015-02-18
  • 2016-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-11
相关资源
最近更新 更多