用 vba 替换文本文件中的整行

Replacing the whole line in a text file with vba

我有一个文本文件,我希望每次宏 运行 时都替换特定的行。该行的开头以“POSTFIXFILENAME;”开头,通常后面有一个日期。我有下面的代码来替换那个特定的词。但是我想替换整行而不是仅仅替换日期总是变化的单词。谢谢你的帮助。

            Dim objFSO
            Const ForReading = 1
            Const ForWriting = 2
            Dim objTS 'define a TextStream object
            Dim strContents As String
            Dim fileSpec As String
            
            'this open notepad and replaces the POSTFIXFILENAME with the required date
            fileSpec = "C:\Program Files (x86)\Traction Software\PDF Content Split SA\Content Split.pcs"
            Set objFSO = CreateObject("Scripting.FileSystemObject")
            Set objTS = objFSO.OpenTextFile(fileSpec, ForReading)
            strContents = objTS.ReadAll

            strContents = Replace(strContents, "POSTFIXFILENAME; ", "POSTFIXFILENAME; " & Datefilename)
            objTS.Close
            
            Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting)
            objTS.Write strContents
            objTS.Close

请试试这个代码:

Private Sub ReplaceTextLine()
    Dim objFSO As Object, objTS As Object, arrTxt, i As Long
    Dim strContents As String, fileSpec As String, sep As String
    Dim Datefilename As String
    
    Datefilename = "What you need here..." 'maybe Range("A2").value 'if I understood your comment
    sep = vbCrLf 'it can be changed with vbCr or VbLf, if different line separator
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    fileSpec = "C:\Program Files (x86)\Traction Software\PDF Content Split SA\Content Split.pcs"

    'all the text is read and transformen in an array, splitting it by vbCrLf (end of line):
    arrTxt = Split(objFSO.OpenTextFile(fileSpec, 1).ReadAll, sep) 'the obtained array
    
    For i = 0 To UBound(arrTxt) 'iterate between the array elements
        If InStr(arrTxt(i), "POSTFIXFILENAME;") > 0 Then   'if one element (line) containes the search string
            arrTxt(i) = "POSTFIXFILENAME; " & Datefilename 'it is replace whith what you need
        End If
    Next i
    'Now the array is joined (retransformed in string) on vbCrLf and written back:
    Set objTS = objFSO.OpenTextFile(fileSpec, 2)
        objTS.write Join(arrTxt, sep)
    objTS.Close
End Sub