VBA Code To Find And Replace Words Within Specific File Names In A Folder

VBA Code To Find And Replace Words Within Specific File Names In A Folder

What This VBA Code Does

I often have a routine of copying files from one month to another. The only problem with this sort of process is I have to go through and modify all the file names to reflect the current month or time period. As you can imagine, this can be quite a timely task....and timely tasks are perfect for automation with VBA!

Macro To Perform Find Replace on File Names

This macro will go through and perform a simple find and replace on all the files within a user selected folder. The macro has three inputs that allow you to customize the find/replace terms, as well as the ability to target specific file types (ie .pdf or .ppt).

The below VBA macro code also uses a custom user-defined function which you will also need to paste into your code module. This function is written out later on in this article. Enjoy!

Sub FileNames_FindReplace()
'PURPOSE: Modify Specific Text Within Files of a Folder
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim FileList As Collection
Dim FileName As Variant
Dim ParentFolder As String
Dim FindTerm As String
Dim ReplaceTerm As String
Dim ExtensionFilter As String
Dim NewFileName As String
Dim ChangeCount As Integer

  FindTerm = "January"
  ReplaceTerm = "February"
  ExtensionFilter = ".xls" 'Leave empty to change all file types

'Retrieve Target Folder Path From User
  'Launch Folder Dialog Box
    Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
    'Record User's Selection
      With FldrPicker
        .Title = "Select A Target Folder"
        .AllowMultiSelect = False
          If .Show <> -1 Then Skip = True
          If Not Skip Then ParentFolder = .SelectedItems(1)
      End With
    'In Case User Cancels
      If ParentFolder = "" Then Exit Sub

'Create a list of files within Specified Folder
  Set FileList = PullFileNames(ParentFolder, "*" & ExtensionFilter & "*")

'Loop through list of files
  For Each FileName In FileList
    If FileName Like "*" & FindTerm & "*" Then
      'Perform Find/Replace on file name
        NewFileName = Replace(FileName, FindTerm, ReplaceTerm)
      'Rename file
        Name FileName As NewFileName
      'Count Changes
        ChangeCount = ChangeCount + 1
    End If
  Next FileName

'Report Results
  MsgBox ChangeCount & " file(s) renamed within folder"

'Open Windows Explorer to see changes (optional)
  Shell "C:\WINDOWS\explorer.exe """ & ParentFolder & "", vbNormalFocus

End Sub

Function To Create List Of Files Within Parent Folder

The below code is also needed as a part of this proccess. The below VBA function creates a Collection (ie list) of all the files within a given parent folder. This list of file names is then passed back to our main VBA macro to change the names of the files.

Private Function PullFileNames(Path As String, Optional FileExt As String = "") As Collection
'PURPOSE: Create A List of Specific Files Within A Folder
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim MyCollection As New Collection
Dim FileName As String

'Ensure folder path has a slash at the end
  If Right(Path, 1) <> "\" Then Path = Path & "\"

'Get first file that meets extension criteria within folder
  FileName = Dir(Path & FileExt)

'Loop through all files in folder
  Do While Len(FileName) > 0
    'Store Filename into a collection (list)
      MyCollection.Add Path & FileName
    'Next file meeting extension criteria (if any left)
      FileName = Dir()
'Output files that meet criteria
  Set PullFileNames = MyCollection

End Function

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it's impossible to account for every particular need one might have. That's why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to getting quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don't have time to fit everyone's questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

~ Chris