Find and replace strings in file names, folder name and subfolders
The following two macros FindReplace() and Recursive() let you rename files and folders recursively based on a search string. The file or folder is renamed if the name contains the search string.
The search string in the file name is replaced by another string you specify. A dialog box appears asking if you want to rename the found file name that matches the search string.
What's on this webpage
1. VBA macros
'Webpage: https://www.get-digital-help.com/find-and-replace-a-text-string-in-file-names-folder-name-and-subfolders/ 'Name macro Sub FindReplace() 'Dimension variables and declare data types Dim myfolder As Variant Dim Fnd As String, Rplc As String 'Display input box and ask for a string to search for Fnd = Application.InputBox(prompt:="Find string:", Title:="Rename files and folders", Type:=2) 'Display another input box and ask for a string to replace with Rplc = Application.InputBox(prompt:="Replace with:", Title:="Rename files and folders", Type:=2) 'Ask for a folder to search With Application.FileDialog(msoFileDialogFolderPicker) .Show myfolder = .SelectedItems(1) & "\" End With 'Start macro Recursive with parameters myfolder, Fnd, and Rplc Call Recursive(myfolder, Fnd, Rplc) End Sub
'Name macro and parameters Sub Recursive(FolderPath As Variant, Fnd As String, Rplc As String) 'Dimension variables and declare data types Dim Value As String, Folders() As String, Fname As String, Fext As String, Mtxt As String Dim x As Integer Dim Folder As Variant, a As Long 'Redimension array variable Folders ReDim Folders(0) 'If ... Then statement 'Check if two last characters equals \\ If Right(FolderPath, 2) = "\\" Then Exit Sub 'Dir function returns a String representing the name of a file, directory, or folder that matches a specified pattern Value = Dir(FolderPath, &H1F) 'Do Until ... Loop statement Do Until Value = "" 'Check if Value is equal to . or .. If Value = "." Or Value = ".." Then 'Continue here if Value is not equal to . or .. Else 'Check if Value is a folder If GetAttr(FolderPath & Value) = 16 Or GetAttr(FolderPath & Value) = 48 Then 'Enable error handling On Error Resume Next 'Concatenate text with value in variable Value and show the new file name Mtxt = "Rename folder " & Value & " to " & WorksheetFunction.Substitute(Value, Fnd, Rplc) & "?" 'Show message box containing buttons Yes, No, and Cancel x = MsgBox(Mtxt, vbYesNoCancel) 'End macro If user press with left mouse button ons Cancel button If x = vbCancel Then Exit Sub 'Check if user press with left mouse button ons Yes If x = vbYes Then 'Rename file if user press with left mouse button ons yes Name FolderPath & Value As FolderPath & WorksheetFunction.Substitute(Value, Fnd, Rplc) End If 'Substitute string specified in Fnd with string in Rplc and save to variable Value Value = WorksheetFunction.Substitute(Value, Fnd, Rplc) 'Check if an error has occurred If Err <> 0 Then 'Show message box containing text "Error" MsgBox "Error" 'Stop macro Exit Sub End If 'Disable error handling On Error GoTo 0 Save string in variable Value to array variable Folders Folders(UBound(Folders)) = Value 'Add another container to array variable Folders ReDim Preserve Folders(UBound(Folders) + 1) 'Continue here if an error has not occurred Else 'Enable error handling On Error Resume Next 'Save extension text to variable Fext Fext = Split(Value, ".")(UBound(Split(Value, "."))) 'Save file name without extension to variable Fname Fname = Left(Value, Len(Value) - Len(Split(Value, ".")(UBound(Split(Value, ".")))) - 1) 'Replace search string (Fnd) with replace string (Rplc) in variable Fname and save to Fname Fname = WorksheetFunction.Substitute(Fname, Fnd, Rplc) 'Check if value is not equal to Fname, dot and Ftext If Value <> (Fname & "." & Fext) Then 'Create text string and save to variable Mtxt Mtxt = "Rename file " & Value & " to " & Fname & "." & Fext & "?" 'Show message box containing text in variable Mtxt with buttons Yes, No, and Cancel. Save result to variable x x = MsgBox(Mtxt, vbYesNoCancel) 'Check if variable x is equal to vbCancel meaning the user press with left mouse button oned Cancel button, stop macro if true If x = vbCancel Then Exit Sub 'Check if user press with left mouse button on Yes If x = vbYes Then 'Rename file Name FolderPath & Value As FolderPath & Fname & "." & Fext End If End If 'Check if an error has occurred If Err <> 0 Then 'Display message box containing text Error MsgBox "Error" 'Stop macro Exit Sub End If 'Disable error handling On Error GoTo 0 End If End If 'Save a new item in current Folder to variable Value Value = Dir 'Go back to Do Until, see above Loop 'Iterate through all folders in array variable Folders For Each Folder In Folders 'Start macro Recursive using folder name and path Call Recursive(FolderPath & Folder & "\", Fnd, Rplc) Next Folder End Sub
2. Where to put the code?
- Press Alt + F11 to open the Visual Basic Editor (VBE), see image above.
- Press with left mouse button on "Insert" on the top menu, a popup menu appears.
- Press with left mouse button on "Module". A new module is created in your workbook.
- Copy VBA code above and paste to code window, see image above.
- Exit VBE and return to Excel.
3. How to start the macro?
- Press Alt + F8, a dialog box appears. See the image above.
- Press with mouse on "FindReplace" to select it.
- Press with left mouse button on "Run" button.
4. What happens when you run macro?
- Type a text string you want to find in the dialog box.
- In the next dialog box, type a text sting you want to replace it with.
- Select a folder, press with left mouse button on OK.
- The macro prompts you each time it finds a file name or folder with the text string you are looking for and ask if you want to rename it.
- Your options are: Yes, No, and Cancel. Cancel exits the macro.
- The macro continues until all files and folders are processed.
The macro does NOT change the file extension name.
Files and folders category
Today I would like to share a macro that compares the content in two different folders and their subfolders. It […]
I will in this article demonstrate a macro that automatically opens all workbooks in a folder and subfolders, one by […]
This is a follow up to my last post Compare file names in two different folder locations and their subfolders, the obvious […]
Excel categories
8 Responses to “Find and replace strings in file names, folder name and subfolders”
Leave a Reply
How to comment
How to add a formula to your comment
<code>Insert your formula here.</code>
Convert less than and larger than signs
Use html character entities instead of less than and larger than signs.
< becomes < and > becomes >
How to add VBA code to your comment
[vb 1="vbnet" language=","]
Put your VBA code here.
[/vb]
How to add a picture to your comment:
Upload picture to postimage.org or imgur
Paste image link to your comment.
Contact Oscar
You can contact me through this contact form
[…] Read the full article here: Find and replace a text string […]
[…] Read the full article here: Find and Replace […]
Hi friends,
I am looking for a macro which will search and replace the complete file name. I have a list of old names in A column and new names in B column. The name of the old files are accruate only until 3 characters. Meaning if the file name is 83a6dfc0-1ce-110-058-e66a514c9effefe.docx then the same file will be in folder with starting "83a*". I want the macro to try finding such similar file names and replace it with new name.
I tried modifying the above codes, but was not successful.
Thanks a Ton in advance !
Hello all,
my search string is 4 and my replace string is 04, but macro keeps asking me if I want to rename "ball" to "ball" or "grass" to "grass" for every file and every folder that doesn't match my search criteria. Is that how it's supposed to work?
Nebojsa,
Did you copy the code or try the file?
Wordpress (website software) changed some characters in the code so perhaps that is the cause to the error you are experiencing.
I also faced same issue of asking non matching folder names
Dear Xlxs tech
I have a list in excel and i want to transfer the list from excel as folder names
how can i do it
How can I turn off it prompting me for each folder or if it would only ask when it finds a folder matching my criteria that would work too? I didn't copy the code because it wouldn't work I downloaded the file and it runs well except for the issue I mentioned. I really appreciate you publishing this it really helps me thanks a ton!!!