我正在编写一个函数,在除了排除的工作表列表之外的工作簿的所有工作表上运行一些宏。我将排除的工作表列表作为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
答案 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
两个注释: