vba-variant:如何处理Class与原始类型
问题描述:
我的函数获取一个集合,并且项目可能是对象或基元 如何将商品分配给变体?
my function gets a collection and the items may be Objects or primitives how can I assign the item to a variant?
我现在所做的看起来像这样:
What I do now looks something like this:
Dim vItem As Variant
On Error Resume Next
vItem = oCollection.Item(sKey)
If Err.Number = 91 Then
Set vItem = oCollection.Item(sKey)
On Error GoTo 0
我认为它可行,但我想知道是否还有更好的方法.
I think it works, but I wonder if there is a better way to do it.
答
您可以使用varType()
函数测试类型,或者,如果要测试特定类型,则可以使用typeof.
You may use the varType()
function to test the type, alternatively if you are testing for specific types, you could use typeof.
If VarType(oCollection.Item(sKey)) = vbObject Then
Set vItem = oCollection.Item(sKey)
Else
vItem = oCollection.Item(sKey)
End If