VBA Rename all files starting with "Rel"

Asked

Viewed 847 times

1

Hello I need to generate a code that renames all files in a folder that start with "relat" to "X-CT". The rest of the file name, including extension ". DOC . PDF . XLS" remained unchanged.

  • This needs to be in the Excel Macro, because the renaming happens after the event of creation of these same files. After renaming, the Macro will generate another batch of files starting with "relat", then need to rename again.... and so on;

1 answer

1

Maybe the code below will help you. Basically, loop the files in a directory and replace, in the name of each file, the string you want to replace with the new.

Follow the code with the edition proposed by the user @Evert:

Sub changeFileName(ByVal srtExtencion as String)

Dim strFolder As String
Dim strFile As String

  strFolder = "C:\SomeFolder\"
  strFile = Dir(strFolder & "\*." & strExtension)
  Do While Len(strFile) > 0
    If InStr(strFile, "relat") > 0 Then
      Name strFolder & strFile As strFolder & Replace(strFile, "relat", "X-CT")
    End If
    strFile = Dir()
  Loop

End Sub

Then call the function with the desired extension:

changeFileName doc
changeFileName pdf
changeFileName xls

I extracted this solution of this forum, together with the edition proposed by the user @Evert

  • I can’t edit your answer... but if you can, edit and code our friend needs and then delete my answer.

  • Edits made! Thanks for the suggestion. Hugs!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.