检查项目是否在ParamArray VBA中

我正在编写一个函数来运行工作簿的所有页面上的一些macros,除了排除的工作表的列表。 我将排除的工作表的列表作为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 

 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 

将VBA作为工具包的一部分工作时,有一个通用的数组searchfunction是非常有用的,因为没有内置的语言。

 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 

然后你可以使用这个函数search一个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循环中,我使用了一个习惯用法来模拟C的“continue”语句 。 您可能会也可能不会欣赏这取决于您的编程风格的喜好。
  2. 这个ArraySearch实现按值传递数组。 这对于支持ParamArrays是必要的。 但是,如果您经常使用它来search数千个元素的巨大数组,那么在这里传递值可能会造成内存或性能问题。