TurboCoder
TurboCoder

Reputation: 1011

VBS - Rename Many Files With Specific Names

I posted originally here:

Rename Files With New Names in Loop

Someone provided a solution which is great:

Dim fso, folder, file, folderName, dict

'Path
folderName = "X:\Test\3rd Party"

'Future FileName
Set dict = CreateObject("Scripting.Dictionary")
dict.Add "MyFile.xlsx", "Mine.xlsx"
dict.Add "YourFile.xlsx", "Yours.xlsx"
dict.Add "HisFile.xlsx", "His.xlsx"
dict.Add "HersFile.xlsx", "Hers.xlsx"
dict.Add "TheirFile.xlsx", "Theirs.xlsx"
dict.Add "OurFile.xlsx", "Ours.xlsx"

' Create filesystem object and the folder object
Set fso = CreateObject("Scripting.FileSystemObject")  
Set folder = fso.GetFolder(folderName)  

' Loop over all files in the folder until the searchFileName is found
For Each file In folder.Files
    If dict.Exists(file.Name) Then file.Name = dict(file.Name)
Next

But the only issue is that is looks for exact file name match. My original post included like 17 if statements within a loop and each if statement used the InStr function to look for partial string match.

The solution above is much cleaner though, so any help with it would be great.

Perhaps just wondering if there is actually a better way of doing what I want too. For example, once a file is renamed, it's excluded from the next loop through?

Upvotes: 0

Views: 288

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

Map the partial strings to the filenames in your dictionary

Set dict = CreateObject("Scripting.Dictionary")
dict.Add "MyFile", "Mine.xlsx"
dict.Add "YourFile", "Yours.xlsx"
dict.Add "His", "His.xlsx"
...

and add a nested loop where you iterate over the partial filenames and check them against the current filename:

For Each file In folder.Files
    For Each str In dict.Keys
        If InStr(str, file.Name) > 0 Then
            file.Name = dict(str)
            Exit For
        End If
    Next
Next

Upvotes: 1

Related Questions