I'm very new to VBA, to start. I have an Excel list of a few hundred values in Column A and what they're supposed to be in Column B but they're spread across hundreds of files.
Essentially I need a find/replace that uses the Excel columns as reference, searches every file in a directory and its subfolders, and makes the find/replace swap.
I'm trying to use a VBA I found elsewhere but it only searches ONE folder, when I need it to search the subdirectories too. The rest of the code is perfect for what I'm doing. Source thread:
https://chandoo.org/forum/threads/multiple-find-and-replace-text-string-files-in-folder.30905/post-184075
Here's what I've been trying so far:
I tried playing around with asterisks\regex with the StrFolder and StrFileName values as a sort of wildcard/catch-all but haven't been able to get it to work for multiple folder levels.
Thank you in advance!
Essentially I need a find/replace that uses the Excel columns as reference, searches every file in a directory and its subfolders, and makes the find/replace swap.
I'm trying to use a VBA I found elsewhere but it only searches ONE folder, when I need it to search the subdirectories too. The rest of the code is perfect for what I'm doing. Source thread:
https://chandoo.org/forum/threads/multiple-find-and-replace-text-string-files-in-folder.30905/post-184075
Here's what I've been trying so far:
Code:
Sub ReplaceStringInFile()
'http://stackoverflow.com/questions/14840574/find-and-replace-string-in-all-excel-files-in-folder
Dim objFSO As Object
Dim objFil As Object
Dim objFil2 As Object
Dim regex As Object: Set regex = CreateObject("VBScript.RegExp")
Dim StrFileName As String
Dim StrFolder As String
Dim strAll As String
Dim FindStr As String, ReplaceStr As String
Set objFSO = CreateObject("scripting.filesystemobject") 'enable microsoft scripting runtime
StrFolder = "C:\Users\me\Top-Level\" 'choose folder to go through
StrFileName = Dir(StrFolder & "*.txt") 'choose extension to find and replace
Do While StrFileName <> vbNullString
Set objFil = objFSO.Opentextfile(StrFolder & StrFileName)
strAll = objFil.readall
objFil.Close
Set objFil2 = objFSO.createtextfile(StrFolder & StrFileName)
For i = 2 To Range("A" & Rows.Count).End(xlUp).Row
With regex
.MultiLine = True
.Global = True
.IgnoreCase = False '\\ Change to true if you don't want case sensitivity
.Pattern = Range("A" & i).Value
strAll = .Replace(strAll, Range("B" & i).Value)
End With
Next i
objFil2.Write strAll 'choose what to find and replace *case sensitive
objFil2.Close
StrFileName = Dir
Loop
Set regex = Nothing
End Sub
Thank you in advance!