Replace Third line of each file inside a folder wi

2019-09-24 10:33发布

I am using the below VBA code to replace few words in all the files inside one folder.in the same VBA code is it possible to copy the third line of each file and replace it with the second line.

Sub ReplaceStringInFile1()

    Dim objFSO As Object, objFil As Object, objFil2 As Object
    Dim StrFileName As String, StrFolder As String, strAll As String, newFileText As String

    Set objFSO = CreateObject("scripting.filesystemobject")
    StrFolder = "I:\Documents\ABC\AZ\"
    StrFileName = Dir(StrFolder & "*.txt")

    Do While StrFileName <> vbNullString
        Set objFil = objFSO.opentextfile(StrFolder & StrFileName)
        strAll = objFil.readall
        objFil.Close
        Set objFil2 = objFSO.createtextfile(StrFolder & StrFileName)
        'change this to that in text
        newFileText = Replace(strAll, "To:", "FROM")
        'change from to to in text
        newFileText = Replace(newFileText, "THIS", "THAT")
        'write file with new text
                'change from to to in text
        newFileText = Replace(newFileText, "IS", "WAS")
        'write file with new text
        objFil2.Write newFileText
        objFil2.Close
        StrFileName = Dir
    Loop
End Sub

1条回答
不美不萌又怎样
2楼-- · 2019-09-24 10:59

I will tell you logic and use the logic accordingly and come up with the code if you got any issues.

Open Each Text file ForReading and read each line one by one using ReadLine and Check for end of stream using AtEndOfStream. Copy each line in one string but skip the second the line. Something like this

Do While Obj.AtEndOfStream <> True
Str = Obj.ReadLine
if i = 2 Then 
Str = ""
Else
StrF = StrF & Vbcrlf & Str 
End If
i = i + 1

Loop

Now Open the Text File ForWritingReplace the old text in files Using Obj.Write StrF and Close the file. Do the loop for all files in the folder.

Hope This Helps :)

查看更多
登录 后发表回答