I wish to open a .docx file from a macro in Excel file, look for all instances of a String in that file and replace that String with another.
I can find and open the file. I do not know if the String has been replaced, because the code below corrupts the file. The file can no longer be opened by Word.
Here is the code for the macro:
Dim objFSO
Dim objTS 'define a TextStream object
Const ForReading = 1
Const ForWriting = 2
Const TristateUseDefault = -2
Dim strContents As String
Dim fileSpec As String
Sub SearchAndReplaceTextInFile()
fileSpec = "C:\some\path\to\file\location\file.docx"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTS = objFSO.OpenTextFile(fileSpec, ForReading, TristateUseDefault)
strContents = objTS.ReadAll
strContents = Replace(strContents, "adress", "address")
Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting, TristateUseDefault)
objTS.Write strContents
objTS.Close
End Sub