Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

vba - Replace Third line of each file inside a folder with second line using Macros

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:DocumentsABCAZ"
    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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...