×

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

By Chris Newman •  Updated: 08/26/16 •  6 min read
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

'Inputs
  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 process. 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()
  Loop
    
'Output files that meet criteria
  Set PullFileNames = MyCollection

End Function

Using VBA Code Found On The Internet

Now that you’ve found some VBA code that could potentially solve your Excel automation problem, what do you do with it? If you don’t necessarily want to learn how to code VBA and are just looking for the fastest way to implement this code into your spreadsheet, I wrote an article (with video) that explains how to get the VBA code you’ve found running on your spreadsheet.

Getting Started Automating Excel

Are you new to VBA and not sure where to begin? Check out my quickstart guide to learning VBA. This article won’t overwhelm you with fancy coding jargon, as it provides you with a simplistic and straightforward approach to the basic things I wish I knew when trying to teach myself how to automate tasks in Excel with VBA Macros.

Also, if you haven’t checked out Excel’s latest automation feature called Power Query, I have put together a beginner’s guide for automating with Excel’s Power Query feature as well! This little-known built-in Excel feature allows you to merge and clean data automatically with little to no coding!

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 get 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 that 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!

Keep Learning

Chris Newman

Chris Newman

Chris is a finance professional and Excel MVP recognized by Microsoft since 2016. With his expertise, he founded TheSpreadsheetGuru blog to help fellow Excel users, where he shares his vast creative solutions & expertise. In addition, he has developed over 7 widely-used Excel Add-ins that have been embraced by individuals and companies worldwide.

[FREE Training] 10 Amazing Excel Efficiency Tricks. Why Don't People Know These?!

X