Reputation: 19371
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.
Upvotes: 3
Views: 766
Reputation: 3827
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))
Upvotes: 0
Reputation: 4363
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
Upvotes: 2