Visual Basic Programming Code Examples
Visual Basic > Files Directories Drives Code Examples
Copying, renaming and deleting files
Copying, renaming and deleting files
The following function shows how to copy, delete and rename files.
Option Explicit
Private Declare Function CopyFile Lib "kernel32" Alias "CopyFileA" (ByVal lpExistingFileName As String, ByVal lpNewFileName As String, ByVal bFailIfExists As Long) As Long
'Purpose : Renames a file
'Inputs : sOriginalName The original path and file name.
' sNewName The new path and file name.
' [bOverWrite] If True will overwrite any other file which might
' have the new file name.
'Outputs : Returns True if succeeded in renaming the file.
'Notes :
'Revisions :
Function FileRename(sOriginalName As String, sNewName As String, Optional bOverWrite As Boolean) As Boolean
On Error GoTo ErrFailed
If Len(Dir$(sOriginalName)) > 0 And Len(sOriginalName) > 0 Then 'Check File Exitsts
If bOverWrite = True And Len(Dir(sNewName)) > 0 Then
'Delete file with same name as new file
VBA.Kill sNewName
End If
Name sOriginalName As sNewName
FileRename = True
End If
Exit Function
ErrFailed:
'Failed to Rename File
FileRename = False
On Error GoTo 0
End Function
'Purpose : Copies a file from one place to another.
'Inputs : sSourceFile The original path and file name.
' sDestinationFile The copy path and file name.
' [bOverWrite] If True will overwrite a file if it exists at the sDestinationFile.
'Outputs : Returns True if succeeded in copying the file.
'Notes : Uses API for speed (can cut copy times by up to 50%)
'Revisions :
Function FileCopy(sSourceFile As String, sDestinationFile As String, Optional bOverWrite As Boolean = True) As Boolean
On Error GoTo ErrFailed
If Len(Dir$(sSourceFile)) Then 'Check File Exitsts
If bOverWrite = False Then
If Len(Dir$(sDestinationFile)) > 0 Then
'File exists, don't overwrite
FileCopy = False
Exit Function
End If
End If
FileCopy = CBool(CopyFile(sSourceFile, sDestinationFile, False)) 'Non zero indicates success
End If
Exit Function
ErrFailed:
'Failed to copy file
Debug.Print "Error in FileCopy: " & Err.Description
FileCopy = False
On Error GoTo 0
End Function
'Purpose : Deletes a file
'Inputs : sFileName The file path and file name to delete
'Outputs : Returns True if succeeded in deleting the file.
'Notes :
'Revisions :
Function FileDelete(sFileName As String) As Boolean
On Error GoTo ErrFailed
If Len(Dir$(sFileName)) > 0 And Len(sFileName) > 0 Then 'Check File Exitsts
'Delete file with same name as new file
VBA.Kill sFileName
FileDelete = True
End If
Exit Function
ErrFailed:
'Failed to delete file
FileDelete = False
On Error GoTo 0
End Function