Everyone is not unfamiliar with VBA processing text files. Open the file, Line Input is read and processed line by line, and then write it to the target file using Print. The whole process is not complicated, but if the source file has a large number of lines, it will take a lot of time to read line by line.
Sub demo() FN1 = FreeFile Open OutFile For Output As FN1 FN2 = FreeFile Open InFile For Input As FN2 Do Until EOF(1) Line Input #1, textline 'Data processing code Print FN2, textline Loop Close FN2 Close FN1 End Sub
VBA built-in method to open text files cannot be used to read all file contents. With the help of FileSystemObject, you can achieve quick replacement at one time.
The sample code is as follows
Sub ReplaceTxt() strSrcFile = "C:\temp\" strOldTxt = "c:\111\" strNewTxt = "d:\333\" Set fso = CreateObject("") Set objRead = (strSrcFile, 1) strIn = Set objWrite = (strSrcFile) Replace(strIn, strOldTxt, strNewTxt) set fso = Nothing End Sub
【Code analysis】
- Line 2 code specifies the source file.
- Line 3 code specifies the string to be found.
- Line 4 code specifies the new string.
- Line 5 code creates the FSO object.
- Line 6 code opens the source file.
- Line 7 calls the readall method to read all file contents and save it in the variable strIn.
- Line 8 code closes the source file.
- Line 9 code creates the target file.
- Line 10 code calls the Replace function to implement full text replacement and writes the result to the target file.
- Line 11 of the code closes the target file.
- The 12th code implements the system resources occupied by object variables.
This is the article about the sample code for VBA to implement quick file replacement. For more related VBA file replacement content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!