Home > How-To Library > File/Folders Handling

How to Rename files (in five ways)

**************************************************************** * © 2007 CodeItBetter http://www.codeitbetter.com * * This notice MUST stay intact for legal use * ****************************************************************
'Using Name Statement: Public Sub RenameFileUsingName(ByVal sOldFileName As String, ByVal sNewFileName 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 file sNewFileName already exists then it will produce an error Name sOldFileName As sNewFileName End Sub 'Using File Copy: Public Sub RenameFileUsingFileCopy(ByVal sOldFileName As String, ByVal sNewFileName 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 file sNewFileName already exists then it will overwrite FileCopy sOldFileName, sNewFileName End Sub 'Using FSO (Method 1): Public Sub RenameFileUsingFSO(ByVal sOldFileName As String, ByVal sNewFileName As String) 'Set a reference to "Microsoft Scripting Runtime" 'If the file sNewFileName already exists then it will overwrite Dim FSO As Scripting.FileSystemObject Set FSO = New Scripting.FileSystemObject FSO.CopyFile sOldFileName, sNewFileName Set FSO = Nothing End Sub 'Using FSO (Method 2): Public Sub RenameFileUsingFSO(ByVal sOldFileName As String, ByVal sNewFileName 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.GetFile(sOldFileName).Name = Mid$(sNewFileName, InStrRev(sNewFileName, "\") + 1) Set FSO = Nothing End Sub 'Using API: Private Declare Function CopyFile Lib "kernel32" Alias "CopyFileA" _ (ByVal lpExistingFileName As String, ByVal lpNewFileName As String, _ ByVal bFailIfExists As Long) As Long Public Sub RenameFileUsingAPI(ByVal sOldFileName As String, ByVal sNewFileName As String) Call CopyFile(sOldFileName, sNewFileName, False) End Sub

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.