我在 Excel 的类模块中创建了一个自定义集合类。我想放置一个函数来用一些自定义对象填充集合,这样我就可以一次传递一个或多个对象。
我创建的函数是:
Public Sub Add( Object1 As customClass, _
Optional Object2 As customClass, _
Optional Object3 As customClass, _
Optional Object4 As customClass, _
Optional Object5 As customClass)
问题是我不知道如何检测传递给函数的参数数量... 我怎样才能检测到它们?
另一方面,我正在尝试这样的事情:
Dim i as integer
for i = 1 to 5
If Not IsMissing("Object" & i) then MyCollection.Add "Object" & i
Next i
...购买显然不起作用。
如何以优雅且简单的方式做到这一点?
最佳答案
If Object2 Is Nothing Then
Debug.Print "obj2 is nothing"
Else
MyCollection.Add Object2
End If
不太漂亮但代码较少的方法是
If Not Object2 Is Nothing then
MyCollection.Add Object2
End if
<小时/>
Public Sub AddExtended(ParamArray arr())
Dim item
Debug.Print "the count: " & UBound(arr) + 1
For Each item In arr
If TypeOf item Is customClass Then
Debug.Print "type of item is customClass"
'MyCollection.Add item
End If
Next
End Sub
例如调用它
Dim o1 As New customClass
Dim o2 As New customClass
Call AddExtended(o1, o2, o2)
'AddExtended o1, o2, o2
<小时/>
您还可以使用自定义集合
关于Excel VBA。如何将对象作为可选参数传递并能够检测它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20095181/