Tin tức mới

Xóa Worksheet bằng VBA từ cơ bản đến nâng cao

1. Xóa 1 sheet theo tên


Sub XoaSheet()
'DisplayAlerts = False để không hiện popup xác nhận
    Application.DisplayAlerts = False
    Worksheets("Sheet1").Delete
    Application.DisplayAlerts = True
End Sub

Xóa một sheet theo tên có kiểm tra sheet tồn tại hay không trước khi xóa:


Sub XoaSheetAnToan()
    Dim ws As Worksheet
    Dim ten As String
    
    ten = "Sheet1"
    
    On Error Resume Next
    Set ws = Worksheets(ten)
    On Error GoTo 0
    
    If Not ws Is Nothing Then
        Application.DisplayAlerts = False
        ws.Delete
        Application.DisplayAlerts = True
    Else
        MsgBox "Sheet không tồn tại!"
    End If
End Sub

2. Xóa sheet đang active


Sub XoaSheetDangMo()
    Application.DisplayAlerts = False
    ActiveSheet.Delete
    Application.DisplayAlerts = True
End Sub

3. Xóa nhiều sheet theo danh sách


Sub XoaNhieuSheet()
    Dim arr
    Dim i As Integer
    
    arr = Array("Sheet1", "Sheet2", "Sheet3")
    
    Application.DisplayAlerts = False
    For i = LBound(arr) To UBound(arr)
        On Error Resume Next
        Worksheets(arr(i)).Delete
        On Error GoTo 0
    Next i
    Application.DisplayAlerts = True
End Sub

4. Xóa tất cả sheet trừ 1 sheet


Sub XoaTatCaTruMot()
    Dim ws As Worksheet
    
    Application.DisplayAlerts = False
    For Each ws In Worksheets
        If ws.Name <> "Main" Then
            ws.Delete
        End If
    Next ws
    Application.DisplayAlerts = True
End Sub

5. Xóa sheet theo điều kiện (ví dụ: tên chứa “Temp”)


Sub XoaSheetTheoDieuKien()
    Dim ws As Worksheet
    
    Application.DisplayAlerts = False
    For Each ws In Worksheets
        If InStr(ws.Name, "Temp") > 0 Then
            ws.Delete
        End If
    Next ws
    Application.DisplayAlerts = True
End Sub

Leave a Reply

Your email address will not be published. Required fields are marked *