Home > How-To Library > File/Folders Handling

How to Rename folder (in three ways)

**************************************************************** * © 2007 CodeItBetter http://www.codeitbetter.com * * This notice MUST stay intact for legal use * ****************************************************************
'Using Name Statement: Public Sub RenameFolderUsingName(ByVal sOldFolderName As String, ByVal sNewFolderName As String) 'Using Name on an open file produces an error. You must close an open 'file before renaming it. Name arguments cannot include multiple-character (*) 'and single-character (?) wildcards. 'If the Folder sNewFolderName already exists then it will produce an error Name sOldFolderName As sNewFolderName End Sub 'Using FSO Method 1: Public Sub RenameFolderUsingFSO(ByVal sOldFolderName As String, ByVal sNewFolderName As String) 'Set a reference to "Microsoft Scripting Runtime" 'If the Folder sNewFolderName already exists then it will overwrite Dim FSO As Scripting.FileSystemObject Set FSO = New Scripting.FileSystemObject FSO.CopyFolder sOldFolderName, sNewFolderName 'It will produce error if any files from this folder is opened/locked FSO.DeleteFolder sOldFolderName, True Set FSO = Nothing End Sub 'Using FSO Method 2: Public Sub RenameFolderUsingFSO(ByVal sOldFolderName As String, ByVal sNewFolderName As String) 'Set a reference to "Microsoft Scripting Runtime" 'If the Folder sNewFolderName already exists then it will overwrite Dim FSO As Scripting.FileSystemObject Set FSO = New Scripting.FileSystemObject sNewFolderName = RemoveBackslash(sNewFolderName) FSO.GetFolder(sOldFolderName).Name = Mid$(sNewFolderName, InStrRev(sNewFolderName, "\") + 1) Set FSO = Nothing End Sub Public Function RemoveBackslash(ByVal sFolder As String) If Right$(sFolder, 1) = "\" Then RemoveBackslash = Left$(sFolder, Len(sFolder) - 1) End If End Function

If you would like to submit your code here please us. Do not forget to mention your name. We are always thankful to each and everyone of you who submitted their code here.