What is the legal use case for a function call on the left side of the assignment?

There is a compilation error in VBA that reads like this:

Function call on left-hand side of assignment must return Variant or Object

Compilation error:

The function call on the left side of the assignment must return a variant or object.

To generate this compilation error, you just need a function:

Public Function Foo(ByVal x As Integer) As Integer
    Foo = x
End Function

      

.. And then a function call on the left side of the assignment - for example:

Public Sub Test()
    Foo(42) = 12
End Sub

      

If I remove the return type As Integer

from the function signature, I get a function that returns implicit Variant

, and the compiler is executed, but now there is a 424 / "Required object" runtime error.

So, I am forcing the function to return the actual object:

Public Function Foo(ByVal x As Integer) As Object
    Dim result As Collection
    Set result = New Collection
    result.Add x
    Set Foo = result
End Function

Public Sub Test()
    Foo(42) = 12
End Sub

      

Now at runtime the error is 438 / "Object doesn't support this property or method" - obviously the method Test

doesn't make any sense.

I can't for the life of me think of anything that would be a valid, legal (and guaranteed?) Use of a function call on a destination LHS.

Compilation error for whatever reason, so there must be a valid use case. What is it?

+3


source to share


2 answers


If the function was to return Variant

and what it Variant

contains Object

(that is, the type Variant

is VT_DISPATCH), and the object has the default property "put", then the assignment is valid, and the assignment is set to this property by default.



In all other cases, this is not the case.

+4


source


VB variant is similar to dynamic in C #, which means that the type is dynamically resolved at runtime. Therefore, it would make sense that you can assign a value to a variant (i.e. the return value of a function that returns the type of a variant).

I guess the use case is very narrow and 99.9% of the time if you try to do it you are doing something wrong.



https://msdn.microsoft.com/VBA/Language-Reference-VBA/articles/function-call-on-left-hand-side-of-assignment-must-return-variant-or-object

+1


source







All Articles