检查项目是否在ParamArray VBA中

时间:2015-04-16 22:53:42

标签: excel vba excel-vba

我正在编写一个函数,在除了排除的工作表列表之外的工作簿的所有工作表上运行一些宏。我将排除的工作表列表作为ParamArray传递,但是在查看ParamArray中列表的当前工作表时遇到了问题。

Public Sub RunThingsOnSheets(ParamArray excludedSheets())

Dim ws as Worksheet
For Each ws In ActiveWorkbook.Worksheets
    If ws Not In excludedSheets Then  'In Pseudocode this is what I want
        "do things"
    End If
Next ws

End Sub

Public Sub Test()

Call RunThingsOnSheets(SheetOne, SheetTwo)

End Sub

2 个答案:

答案 0 :(得分:3)

Public Sub RunThingsOnSheets(ParamArray excludedSheets())
Dim ws As Worksheet, o, inList As Boolean

    For Each ws In ActiveWorkbook.Worksheets
        inList = False
        For Each o In excludedSheets
            If o.Name = ws.Name Then
                inList = True
                Exit For
            End If
        Next
        If Not inList Then
            Debug.Print "not in excludedsheets: " & ws.Name
        End If
    Next ws

End Sub

Public Sub Test()

    RunThingsOnSheets Sheet1, Sheet3

End Sub

答案 1 :(得分:2)

在使用VBA作为工具包的一部分时,拥有通用数组搜索功能很有用,因为该语言没有内置。

Public Function ArraySearch(ByVal a As Variant, v As Variant, _
                            Optional ByRef found_index As Variant) As Boolean
    Dim i As Long

    ArraySearch = False

    If Not IsArray(a) Then Exit Function

    For i = LBound(a) To UBound(a)
        If (VarType(a(i)) And vbArray) <> 0 Then
            ' Don't compare arrays
        ElseIf (VarType(v) And vbArray) <> 0 Then
            ' Don't compare arrays
        ElseIf VarType(a(i)) = VarType(v) Then
            If IsObject(v) Then
                If a(i) Is v Then
                    ArraySearch = True
                    Exit For
                End If
            ElseIf a(i) = v Then
                ArraySearch = True
                Exit For
            End If
        ElseIf VarType(a(i)) = vbError Or _
            VarType(v) = vbError Or _
            VarType(a(i)) = vbObject Or _
            VarType(v) = vbObject _
        Then
            ' Guard against type mismatch
        ElseIf a(i) = v Then
            ArraySearch = True
            Exit For
        End If
    Next

    If ArraySearch And Not IsMissing(found_index) Then found_index = i
End Function

然后你可以使用这个函数搜索ParamArray。

Public Sub RunThingsOnSheets(ParamArray excludedSheets())
    Dim ws as Worksheet

    For Each ws In ActiveWorkbook.Worksheets: Do
        If ArraySearch(excludedSheets, ws) Then Exit Do

        ' do things
    Loop While False: Next
End Sub

两个注释:

  1. 我在For Each循环中使用了idiom to simulate C's "continue" statement。您可能会也可能不会欣赏这一点,具体取决于您的编程风格偏好。
  2. 此ArraySearch实现按值传递数组。这是支持ParamArrays所必需的。但是,如果您经常使用它来搜索数千个元素的大量数组,那么在此处传递值可能会产生内存或性能问题。