Có nhiều cách để xóa file text trong VBA. Hãy xem các ví dụ sau đây:
Ví dụ 1: Xóa file text trong VBA bằng cách 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.text"
If (fso.FileExists(fileName)) Then
fso.DeleteFile fileName, True
End If
End Sub
Ví dụ 2: Xóa file text trong VBA bằng cách sử dụng lệnh Kill.
Sub deleteExcelFileExample2()
Dim currentPath As String
Dim fileName As String
Dim test As String
currentPath = Application.ActiveWorkbook.Path
fileName = currentPath & "\" & "test1.txt"
' delete fileName
test = Dir(fileName)
If Not test = "" Then
Kill (fileName)
End If
End Sub