'********************************************************************************************************** ' Name: deleteFile ' Author: mielk | 2012-10-14 ' ' Comment: Function to delete the specified file from the file system. ' ' Parameters: ' filepath The path of a file to be deleted. ' ' Returns: ' Boolean True - if the given file has been deleted or the given file doesn't exist. ' False - if it was impossible to delete the given file (i.e. it is being used at ' this moment). ' ' ' --- Changes log ----------------------------------------------------------------------------------------- ' 2012-10-14 mielk Function created. '********************************************************************************************************** Public Function deleteFile(filepath As String) As Boolean Const METHOD_NAME As String = "deleteFile" Const ERR_NUM_FILE_NOT_FOUND As Long = 53 '------------------------------------------------------------------------------------------------------ Static objFSO As Object '(Late binding that allows to use the function, even if 'Microsoft Scripting Runtime library is not loaded) '------------------------------------------------------------------------------------------------------ 'Create FileSystemObject instance if it hasn't been created yet. ------------------------------------| If objFSO Is Nothing Then '| Set objFSO = VBA.CreateObject("Scripting.FileSystemObject") '| End If '| '----------------------------------------------------------------------------------------------------| 'Try to remove the given file. If it is not possible code moves to the DeleteFileException label. ---| On Error GoTo DeleteFileException '| Call objFSO.deleteFile(filepath) '| deleteFile = True '| '----------------------------------------------------------------------------------------------------| '========================================================================================================== ExitPoint: Exit Function '---------------------------------------------------------------------------------------------------------- DeleteFileException: If VBA.Err.number = ERR_NUM_FILE_NOT_FOUND Then 'File cannot be deleted because it doesn't exist. In this case True should be returned. deleteFile = True Else 'File cannot be deleted for any other reason. deleteFile = False End If GoTo ExitPoint End Function