vba-variant: how to handle Class vs. primitive types

依然范特西╮ 提交于 2019-12-12 09:54:59

问题


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.


回答1:


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



回答2:


A slight improvement to the answer from @SWa is to create a helper function; this avoids having to copy/paste, for example, the oCollection.Item(sKey) part of op's answer.

Sub SetThisToThat(ByRef this As Variant, ByRef that As Variant)
    If IsObject(that) Then
        Set this = that
    Else
        this = that
    End If
End Sub

Some tests as an example:

Function Test()
    Call SetThisToThat(Test, "Function test")
End Function

Sub RunTest()
    MsgBox Test

    Dim s As String
    Call SetThisToThat(s, "Why must it be this hard?")
    MsgBox s
End Sub

@TmTron should use:

Call SetThisToThat(vItem, oCollection.Item(sKey))


来源:https://stackoverflow.com/questions/21572437/vba-variant-how-to-handle-class-vs-primitive-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!