我原来在这里发布:
Rename Files With New Names in Loop
有人提供了一个很棒的解决方案:
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
但唯一的问题是寻找确切的文件名匹配。我的原始帖子包含了一个循环中的17个if语句,每个if语句使用InStr
函数来查找部分字符串匹配。
上面的解决方案更加清晰,所以任何帮助都会很棒。
也许只是想知道是否真的有更好的方式来做我想做的事情。例如,一旦文件被重命名,它就会被排除在下一个循环中?
答案 0 :(得分:1)
将部分字符串映射到字典中的文件名
Set dict = CreateObject("Scripting.Dictionary")
dict.Add "MyFile", "Mine.xlsx"
dict.Add "YourFile", "Yours.xlsx"
dict.Add "His", "His.xlsx"
...
并添加一个嵌套循环,迭代部分文件名并根据当前文件名检查它们:
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