过滤函数导致编译错误

时间:2017-11-08 16:52:15

标签: vba excel-vba filter excel

我正在尝试使用过滤功能删除列表中的所有工作表not 但我收到了错误

Compile error: Wrong number of arguments or invalid property assignment

我看不出有什么问题

感谢您对此提供的任何帮助

Sub DelShtsNotInList()
Dim Arr
Dim Sht As Worksheet

Arr = Array("A", "B", "C")

Application.DisplayAlerts = False
    For Each Sht In Worksheets
        If Not UBound(filter(Arr, "A", True, vbTextCompare)) >= 0 Then 
           Sht.Delete
        End if
    Next Sht
Application.DisplayAlerts = True

End Sub

2 个答案:

答案 0 :(得分:1)

这似乎工作正常:

Sub DelShtsNotInList()
    Dim Arr
    Dim Sht As Worksheet

    Arr = Array("A", "B", "C")

    Application.DisplayAlerts = False
    For Each Sht In Worksheets
        If Not UBound(Filter(Arr, Sht.Name, True, vbTextCompare)) >= 0 Then
            Sht.Delete
        End If
    Next Sht
    Application.DisplayAlerts = True

End Sub

注意:请注意,不允许删除最后一个工作表,因此如果所有名称都匹配,则会发生运行时错误。

答案 1 :(得分:1)

我认为编译错误来自其他SubFunction,这个应该没问题。但是,试试这样:

Sub DelShtsNotInList()

    Dim Arr As Variant
    Dim Sht As Worksheet

    Arr = Array("A", "B", "C")

    Application.DisplayAlerts = False
    For Each Sht In Worksheets
        If Not UBound(Filter(Arr, Sht.Name, True, vbTextCompare)) >= 0 Then
            If Worksheets.Count = 1 Then
                MsgBox "Error is coming"
                Exit Sub
            End If
            Sht.Delete
        End If
    Next Sht
    Application.DisplayAlerts = True

End Sub

如果您尝试删除最后一个工作表,if将为您提供一个msgbox。