Bạn có thể xóa thư mục trong VBA bằng việc sử dụng đối tượng Scripting.FileSystemObject hoặc lệnh RmDir. Hãy xem các ví dụ sau đây:
Ví dụ 1: Sử dụng đối tượng Scripting.FileSystemObject để xóa thư mục trong VBA.
Sub deleteFolderExample1()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim currentPath As String
Dim folderTest As String
currentPath = Application.ActiveWorkbook.Path
folderTest = currentPath & "\" & "test"
' create folder "test" if not exists
If (fso.FolderExists(folderTest)) Then
fso.DeleteFolder (folderTest)
End If
End Sub
Ví dụ 2: Sử dụng lệnh RmDir để xóa thư mục trong VBA.
Sub deleteFolderExample2()
Dim currentPath As String
Dim folderTest As String
currentPath = Application.ActiveWorkbook.Path
folderTest = currentPath & "\" & "test2"
' create folder "test2" if not exists
If Dir(folderTest, vbDirectory) <> "" Then
RmDir folderTest
End If
End Sub