适用条件:在某一目录下有许多文件夹,希望替换文件夹名称里的某个字符
使用说明:在该目录下新建一个excel文件,并将下述代码复制VBA代码中
Sub RenameFolders_LastTwoChars()
Dim folderPath As String
Dim fso As Object
Dim folder As Object
Dim folderName As String
Dim newFolderName As String
Dim lastTwoChars As String
Dim modifiedLastTwoChars As String
' 获取当前Excel文件所在的目录
folderPath = ThisWorkbook.Path & "\"
' 创建文件系统对象
Set fso = CreateObject("Scripting.FileSystemObject")
' 遍历Excel所在目录的所有文件夹
For Each folder In fso.GetFolder(folderPath).SubFolders
folderName = folder.Name
' 获取最后两个字符
If Len(folderName) >= 2 Then
lastTwoChars = Right(folderName, 2)
Else
lastTwoChars = folderName ' 处理文件夹名长度小于2的情况
End If
' 仅替换最后两个字符中的 "A" 为 "0"
modifiedLastTwoChars = Replace(lastTwoChars, "A", "0")
' 组合新的文件夹名
newFolderName = Left(folderName, Len(folderName) - Len(lastTwoChars)) & modifiedLastTwoChars
' 确保新文件夹名不同,避免无意义重命名
If newFolderName <> folderName Then
' 重命名文件夹
On Error Resume Next
Name folderPath & folderName As folderPath & newFolderName
If Err.Number <> 0 Then
MsgBox "无法重命名:" & folderName, vbExclamation
Err.Clear
End If
On Error GoTo 0
End If
Next folder
' 释放对象
Set fso = Nothing
MsgBox "文件夹重命名完成!", vbInformation
End Sub