vba变体:如何处理类与基元类型

vba变体:如何处理类与基元类型,vba,object,variant,Vba,Object,Variant,my函数获取一个集合,这些项可能是对象或基本体 如何将项目分配给变体 我现在所做的事情如下所示: 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 我认为它是有效的,但我想知道是否有更好的方法。您可以使用varType()函数来测试类型,或者,

my函数获取一个集合,这些项可能是对象或基本体 如何将项目分配给变体

我现在所做的事情如下所示:

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

我认为它是有效的,但我想知道是否有更好的方法。您可以使用
varType()
函数来测试类型,或者,如果您正在测试特定类型,则可以使用typeof

        If VarType(oCollection.Item(sKey)) = vbObject Then
           Set vItem = oCollection.Item(sKey)
        Else
            vItem = oCollection.Item(sKey)
        End If

对@SWa的答案的一个轻微改进是创建一个helper函数;这避免了复制/粘贴op答案的
oCollection.Item(sKey)
部分

Sub SetThisToThat(ByRef this As Variant, ByRef that As Variant)
    If IsObject(that) Then
        Set this = that
    Else
        this = that
    End If
End Sub
以一些测试为例:

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应使用:

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

这会起作用,但我需要一个解决方案来使用
oCollection.Item(sKey)
。正如Mark Nold所解释的那样,它要快得多(特别是因为我将拥有大量的集合),那么:
如果VarType(oCollection.Item(sKey))=vbObject
?是的-当然,这很有效(对我来说似乎很容易…)类型检查与
IsObject(oCollection.Item(sKey))