sigil
sigil

Reputation: 9546

How to assign a function value to a variant if that function may return an object?

I'm assigning a value to a variable, where that value is either a number or an object instance depending on the result of a server request, as follows:

Sub assignVar()

Dim v As Variant

v = getValue

End Sub

Function getValue() As Variant

Dim result As Boolean

result = PostSomethingToServer()
If result Then
    getValue = 1
Else
    Set getValue = New Dictionary
    getValue.Add "a", 1
End If

End Function

This works fine if I call assignVar(true), but if I call assignVar(false) then I get the error:

Wrong number of arguments or invalid property assignment

which is to be expected, because if getValue() returns an object, it should be assigned as set v = getValue. But if I write it this way, then I get a Type mismatch error because I'm trying to assign an integer using a Set statement.

How can I make sure that v gets assigned correctly for either return value of getValue()?

Upvotes: 1

Views: 153

Answers (1)

sigil
sigil

Reputation: 9546

For now I'm resolving this by adding a ReturnValue class:

Option Explicit

Public value As Variant
Public valueIsObject As Boolean

Public Sub setup(value As Variant)

If IsObject(value) Then
    Set Me.value = value
    valueIsObject = True
Else
    Me.value = value
    valueIsObject = False
End If

End Sub

This way, I can rewrite the test methods as follows:

Sub assignVar()

Dim v As Variant
Dim rv as ReturnValue

Set rv = getValue

If rv.valueIsObject Then
    Set v = rv.value
Else
    v = rv.value
End If

End Sub

Function getValue() As ReturnValue

Dim result As Boolean
Dim dict as Dictionary

result = PostSomethingToServer()

set getValue=new ReturnValue

If result Then
    getValue.setup 1
Else
    Set dict = New Dictionary
    dict.Add "a", 1
    getValue.setup dict
End If

End Function

Upvotes: 1

Related Questions