Search code examples
vbaexcelobjectvariant

Write result of function to a variable, where result could be an object


If I have a function which may return an object or a primitive type - within it I can do the following to handle those two cases:

Function Result() As Variant 'may be object or not
    '... get item - the return value
    If IsObject(item) Then
        Set Result = item
    Else
        Result = item
    End If
End Function

However, how can I do the same test for the variable where Result is stored without running the function two times? Eg

Dim myResult As Variant
If IsObject(Result) Then 'test return type of function
    Set myResult = Result
Else
    myResult = Result
End If

As

myResult = Result 'fails if Result returns object
Set myResult = Result 'fails if Result returns non-object

I am trying to write a series of objects/non objects to an array of variant type


Solution

  • Well one possible solution is to write to the variable directly, by passing it ByRef. In a standard module:

    Property Let LetSet(ByRef variable As Variant, ByVal value As Variant)
        If IsObject(value) Then
            Set variable = value
        Else
            variable = value
        End If
    End Sub
    

    called like

    Dim myResult As Variant
    LetSet(myResult) = 123                'myResult = 123
    LetSet(myResult) = New Collection     'Set myResult = New Collection