I have harvested the following code from the link below and would like to enable it to make a given change to all text files in a selected folder.
Advice welcome.
mark
http://www.jpsoftwaretech.com/find-and-replace-in-text-files/
Advice welcome.
mark
http://www.jpsoftwaretech.com/find-and-replace-in-text-files/
Code:
Sub FindAndReplace(filePath As String, findWhat As String, _
replaceWith As String)
' from Excel Help:
' A variable-length string can contain up to approximately 2 billion
' (2^31) characters.
Dim nextFileNum As Long
Dim oldFileContents As String
Dim newFileContents As String
Dim textFileTypes() As String
Dim fileExtension As String
If Len(Dir(filePath)) = 0 Then
Exit Sub
End If
' only act on "text" files
textFileTypes = QuoteString("txt csv html xml", ",")
fileExtension = LCase$(Right$(filePath, 3))
If UBound(Filter(textFileTypes, fileExtension)) = -1 Then
Exit Sub
End If
' open file and read contents
nextFileNum = FreeFile
Open filePath For Input As #nextFileNum
oldFileContents = Input$(LOF(nextFileNum), #nextFileNum)
Close #nextFileNum
' replace old char with new char
newFileContents = Replace(oldFileContents, findWhat, replaceWith)
' reopen file and write new contents
nextFileNum = FreeFile
Open filePath For Output As #nextFileNum
Print #nextFileNum, newFileContents
Close #nextFileNum
End Sub
Function QuoteString(str As String, delimiter As String) As String()
Dim tempString() As String
Dim newString As String
newString = Replace(str, " ", delimiter)
' split the string into an array, using delimiter
tempString = Split(newString, delimiter)
QuoteString = tempString
End Function
Sub TestFindAndReplace()
On Error GoTo ErrorHandler
Call FindAndReplace("V:\Mark\VBA_Excel\test data app\Sample Data\ReplaceInTextFile.txt", "UnderwriterName=IPA", "coolio")
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub