VBA自动化错误:-2147221080(800401a8)

时间:2018-08-01 09:08:58

标签: excel-vba

我的代码有问题,即尽管存在工作表,但只有一行会不断出现自动化错误,但一切正常。我的代码应该基于某个名称列删除工作表,尽管对其进行了编辑,但仍然会发生错误。如果有人可以在这里帮助我,将非常感谢!

Sub DeleteSelectedSheets()

Const lngNameCol = 8 ' names in column (H)
' lngRow = 5 ' data start in row 5

Dim i As Long
Dim lastrow As Long
Dim row_num As Long

Dim wsh_to_delete As Worksheet
Dim main_sheet As Worksheet
Dim ws As Worksheet

Set main_sheet = ActiveSheet

lastrow = main_sheet.Range("A" & main_sheet.Rows.Count).End(xlUp).Row

Application.ScreenUpdating = False

For Each ws In ActiveWorkbook.Worksheets

    For row_num = 5 To lastrow
        If Not ws Is Nothing Then
            If ws.Name = main_sheet.Cells(row_num, lngNameCol).Value Then
                On Error Resume Next
                Application.DisplayAlerts = False
                Worksheets(ws.Name).Delete
                Application.DisplayAlerts = True
                On Error GoTo 0
            End If
        End If
    Next
Next

End Sub

此处发生自动化错误:

If ws.Name = main_sheet.Cells(row_num, lngNameCol).Value Then

尽管代码删除了工作表,但错误仍在每一行之后弹出

2 个答案:

答案 0 :(得分:0)

我认为问题出在循环期间删除工作表。

反过来试试循环,遍历每张纸,看看它是否是您想要的名称:

For row_num = 5 To lastrow
    For Each ws In ActiveWorkbook.Worksheets
        If Not ws Is Nothing Then
            If ws.Name = main_sheet.Cells(row_num, lngNameCol).Value Then
                On Error Resume Next
                Application.DisplayAlerts = False
                Worksheets(ws.Name).Delete
                Application.DisplayAlerts = True
                On Error GoTo 0
            End If
        End If
    Next
Next

答案 1 :(得分:0)

从集合中删除元素时,整个集合有些“不愉快”。对于工作表,最好的方法是将工作表的总数循环到1,并检查是否应删除工作表:

Sub TestMe()

    Dim i As Long
    For i = Worksheets.Count To 1 Step -1
        If Worksheets(i).Name = "Something" And Worksheets.Count > 1 Then
            Application.DisplayAlerts = False
            Worksheets(i).Delete
            Application.DisplayAlerts = True
        End If
    Next

End Sub

另外,Worksheets.Count>1有一个规则,因为不能删除工作簿的最后一个工作表。