excel 删除基于A1单元格值的工作表

mklgxw1f  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(169)

下面的代码用于删除单元格A1中显示Delete的每个选项卡。
我不明白的是,在一个工作簿,它的工作和下一个工作簿,它给我运行时错误13类型不匹配给予。
请让我知道,如果你看到为什么我收到运行时错误13。

Sub DeleteTabs()
    Dim ws As Worksheet
    Application.DisplayAlerts = False
    
    For Each ws In ThisWorkbook.Sheets
        If ws.Cells(1, 1).Value = "Delete" Then
            ws.Delete
        End If
    Next ws
    
    Application.DisplayAlerts = True
End Sub

字符串

xlpyo6sf

xlpyo6sf1#

删除单元格中包含字符串的工作表

Sub DeleteWorksheets()
    
    Const PROC_TITLE As String = "Delete Worksheets"
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    
    Dim wsCount As Long: wsCount = wb.Worksheets.Count
    
    Dim ws As Worksheet, w As Long, ErrorNumber As Long, Msg As String
    
    For w = wsCount To 1 Step -1
        Set ws = wb.Worksheets(w)
        If StrComp(CStr(ws.Range("A1").Value), "Delete", vbTextCompare) = 0 Then
            Application.DisplayAlerts = False
                On Error Resume Next
                    ws.Delete
                    ErrorNumber = Err.Number
                On Error GoTo 0
            Application.DisplayAlerts = True
            If ErrorNumber <> 0 Then
                Msg = Msg & vbLf & vbTab & ws.Name
            End If
        End If
    Next w

    If Len(Msg) > 0 Then
        Msg = "The following worksheet(s) could not be deleted:" & vbLf & Msg
        MsgBox Msg, vbExclamation, PROC_TITLE
    Else
        MsgBox "All worksheets deleted.", vbInformation, PROC_TITLE
    End If
        
End Sub

字符串

blmhpbnm

blmhpbnm2#

  • Sheets集合,表示所有工作表(包括工作表和图表工作表)
  • Dim ws As Worksheet,即。ws被定义为工作表对象。如果工作簿中有图表工作表,For循环交互将引发错误13。

如果您也想删除图表工作表,

Sub DeleteTabs()
    Dim ws As Object
    Application.DisplayAlerts = False
    For Each ws In ThisWorkbook.Sheets
        If TypeName(ws) = "Chart" Then
            ws.Delete ' modify as needed
        Else
            If ws.Cells(1, 1).Value = "Delete" Then
                ws.Delete
            End If
        End If
    Next ws
    Application.DisplayAlerts = True
End Sub

字符串
或者,你只关心工作表。

Sub DeleteTabs()
    Dim ws As Worksheet
    Application.DisplayAlerts = False
    For Each ws In ThisWorkbook.Worksheets
        If ws.Cells(1, 1).Value = "Delete" Then
            ws.Delete
        End If
    Next ws
    Application.DisplayAlerts = True
End Sub

  • Microsoft文档:*

Workbook.Sheets property (Excel)

注意:如果你想有一个更可靠的方法来比较单元格值,请参考@VBasic2008的回复。

相关问题