Có nhiều cách để delete file excel trong VBA. Hãy xem các ví dụ dưới đây:
Ví dụ 1: xóa excel file trong vba sử dụng Scripting.Runtime library.
Sub deleteExcelFileExample1() Dim fso As Object Set fso = CreateObject("Scripting.FileSystemObject") Dim currentPath As String Dim fileName As String currentPath = Application.ActiveWorkbook.Path fileName = currentPath & "\" & "test1.xlsx" If (fso.FileExists(fileName)) Then fso.DeleteFile fileName, True End If End Sub
Ví dụ 2: Sử dụng phương thức Kill.
Sub deleteExcelFileExample2() Dim currentPath As String Dim fileName As String Dim test As String currentPath = Application.ActiveWorkbook.Path fileName = currentPath & "\" & "test1.xlsx" ' delete fileName test = Dir(fileName) If Not test = "" Then Kill (fileName) End If End Sub