求助:使用VBA批量重命名文件夹时出现运行时错误'91'
Hey there! Let's work through that Error 91 issue you're hitting with your VBA folder renaming code. I've been there as a VBA newbie—those object variable errors can be tricky, but we'll fix this step by step.
First, let's clear up what Error 91 means: it pops up when you try to use an object variable that hasn't been properly set (like it's still Nothing instead of pointing to a valid folder or file system object). For folder tasks, this usually happens if you skip initializing the FileSystemObject or reference a folder that doesn't exist.
Here's a working, error-handled version of the code
This will remove the special characters you listed, handle missing folders, and avoid duplicate names:
Sub RemoveSpecialCharsFromFolders() Dim fso As Object Dim targetFolder As Object Dim subFolder As Object Dim newFolderName As String Dim charToRemove As Variant Dim forbiddenChars As Variant ' Initialize the FileSystemObject (critical to avoid Error 91!) Set fso = CreateObject("Scripting.FileSystemObject") ' Replace this with your actual root folder path Dim targetPath As String targetPath = "C:\Your\Actual\Folder\Path" ' Check if the target folder exists On Error Resume Next Set targetFolder = fso.GetFolder(targetPath) On Error GoTo 0 If targetFolder Is Nothing Then MsgBox "Oops! The folder path you entered doesn't exist. Double-check it and try again.", vbExclamation Exit Sub End If ' List of special characters to remove (add/remove as needed) forbiddenChars = Array("-", ":", ";", "/", "\", "*", "?", """", "<", ">", "|") ' Loop through every subfolder in your target folder For Each subFolder In targetFolder.SubFolders newFolderName = subFolder.Name ' Strip out each forbidden character For Each charToRemove In forbiddenChars newFolderName = Replace(newFolderName, charToRemove, "") Next charToRemove ' Only rename if the name actually changed If newFolderName <> subFolder.Name Then ' Handle duplicate names (add a number suffix if needed) Dim counter As Integer counter = 1 Dim tempName As String tempName = newFolderName Do While fso.FolderExists(subFolder.ParentFolder.Path & "\" & tempName) tempName = newFolderName & " (" & counter & ")" counter = counter + 1 Loop ' Rename the folder subFolder.Name = tempName ' Print to Immediate Window for debugging (press Ctrl+G in VBA editor to see) Debug.Print "Renamed: " & subFolder.Name & " → " & tempName End If Next subFolder MsgBox "All done! Folders have been cleaned up.", vbInformation End Sub
Key fixes that solve Error 91
Properly initialize the FileSystemObject:
The lineSet fso = CreateObject("Scripting.FileSystemObject")is non-negotiable. Without it,fsois an uninitialized object, which triggers Error 91 when you try to use methods likeGetFolder.Validate your target folder:
We added error handling to check if the folder path you entered is valid. IfGetFolderfails (e.g., typos in the path),targetFolderstaysNothing—we catch this and show a friendly message instead of crashing.Avoid empty object references:
Before looping through subfolders, we confirmtargetFolderis a valid object. Skipping this check would cause Error 91 if the folder doesn't exist.
What you might have missed in your original code
Chances are you either:
- Forgot to set the
FileSystemObject(noSet fso = ...line), or - Tried to access a folder without checking if it exists first, leaving
targetFolderasNothing.
Quick tips before running
- Test on a copy first: Make a duplicate of your folders to test the code—better safe than sorry!
- Update the folder path: Replace
"C:\Your\Actual\Folder\Path"with the real path to your root folder. - Check the Immediate Window: Press
Ctrl+Gin the VBA editor to see a log of all renamed folders.
内容的提问来源于stack exchange,提问作者John.doe

