VBA文件夹重命名

时间:2018-02-21 15:48:42

标签: vba rename directory

我希望使用VBA重命名一组文件夹。目的是从文件夹名称中删除特殊字符,例如 - :; /,等。这是我到目前为止所做的:

Sub File_renaming2()
Dim objFSO As FileSystemObject, myObj As Object, mySource As Object, Folder As Variant
Set mySource = myObj.GetFolder("C:\Users\John.Doe\Desktop\ABC\VBA Test folder")

For Each Folder In mySource.Folder
    Folder.Name.Replace What:="-", Replacement:=" " 'replace - with space
    Folder.Name.Replace What:=":", Replacement:=" " 'replace : with space
    Folder.Name.Replace What:=";", Replacement:=" " 'replace ; with space
    Folder.Name.Replace What:="/", Replacement:=" " 'replace / with space

    Next Folder

End Sub

我是VBA的新手,并在网上找到类似问题解决方案的代码,但这似乎给了我

  

运行时错误' 91' - 对象变量或未设置块变量。

感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:2)

已修改:用户反馈后

你必须在使用之前设置所有对象变量

你必须与你为他们选择的名字保持一致......(myObj shoudl be objFSO

按照以下代码

Option Explicit

Sub File_renaming2()
    Dim objFSO As FileSystemObject, myObj As Object, mySource As Object, Folder As Variant
    Dim newName As String

    Set objFSO = New FileSystemObject
    Set mySource = objFSO.GetFolder("C:\Users\John.Doe\Desktop\ABC\VBA Test folder")

    For Each Folder In mySource.SubFolders
        newName = Folder.name
        newName = Replace(newName, "-", " ")  'replace - with space
        newName = Replace(newName, ":", " ")  'replace : with space
        newName = Replace(newName, ";", " ")  'replace ; with space
        newName = Replace(newName, "/", " ")  'replace / with space
        If Folder.name <> newName Then Folder.name = newName ' assign new name. the check is to (possibly) ensure you're not processing the same folder twice
    Next Folder
End Sub

因为似乎FSO不允许在同一&#34;会话&#34;中更改两次相同文件夹的名称。