Reputation: 13
I am looking to use VBA to rename a set of folders. The purpose is to remove special characters from the folder names such as - : ; /, etc. Here is what I have so far:
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
I am new to VBA and made the code off of the solutions to similar questions online, but this appears to give me
run-time error '91'- Object variable or With block variable not set.
Any help is appreciated, thanks!
Upvotes: 1
Views: 6470
Reputation: 13386
edited: after user feedback
you have to set all object variables before using them
and you have to be consistent with the name you chose for them... (myObj
shoudl be objFSO
)
as per following code
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
since it seems FSO would not allow to change twice the name of the same folder in the same "session".
Upvotes: 4