Minggu, 26 Mei 2019

Delete Files Using VBA

Gambar 233.M3

VBA Delete Files Macro helps to Delete Files using VBA from a folder. 

Generally while dealing with the file operations we create or delete files using VBA in the process. 

For example when we are automating a specific task, we create lot of intermediate files and finally we produce one final output. At end we clean or delete all the intermediate files using VBA.

Sometimes we may regularly monitor outlook and when we receive a new mail with required input files. We will save these files in a specific folder to process these files and produce the final output.

And we will check before saving the input files in the folder and delete if there are any existing files are already available in the directory.


Solution(s):

We can use DeleteFile method of FileSystemObject to delete files using VBA. Following are the examples to delete a specific file or files from a location.

VBA Delete Files Macro – Example Cases:

Delete a specific file from a folder

Following is the example to delete a specific file from a folder or a directory.You can use DeleteFile method of FileSystemObject to Delete a specific file from a folder.

First it will check whether the file exists in the sourse location or not. If it exists it will delete from the directory ot it will display message.

Code:'In this Example I am deleting a File 'Sample.xls' which exists in the same location of the macro file 

Sub sbDeletetingAFile() 
Dim FSO 
Dim sFile As String 'Source File Location 

sFile = "D:\Job\" & "Sample.xls" 'You can change this Loaction 

'Set Object 
Set FSO = CreateObject("Scripting.FileSystemObject") 

'Check File Exists or Not 
If FSO.FileExists(sFile) Then 
'If file exists, It will delete the file from source location 
FSO.DeleteFile sFile, True  
MsgBox "Deleted The File Successfully", vbInformation, "Done!" 
Else 
'If file does not exists, It will display following message 
MsgBox "Specified File Not Found", vbInformation, "Not Found!" 
End If 
End Sub 

Output:

Case 1: 
If file does not exists in the source location to delete, It will display following message.



Case 2: 
If file is exists in the source location, It will delete the file from source location. And it will display following message.




Tidak ada komentar:

Posting Komentar

Catatan: Hanya anggota dari blog ini yang dapat mengirim komentar.