How to Rename files (in five ways)
Posted on January 4, 2009
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | 'File/Folder Handling - How to Rename files (in five ways) '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 |