What's a legit use case for a function call to be on left-hand side of assignment?

Viewed 452

There's a compile error in VBA that reads as follows:

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

Compile error:

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

To produce this compile 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-hand side of an assignment - for example:

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

If I remove the As Integer return type from the function's signature, I get a function that returns an implicit Variant, and the compiler is satisfied - but now there's a run-time error 424 / "Object Required".

So I make the function return an 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 run-time the error is 438 / "Object doesn't support this property or method" - obviously, that Test method makes no sense whatsoever.

I cannot for the life of me think of anything that would be a valid, legitimate (and warranted?) use of a function call on the LHS of an assignment.

That compile error exists for a reason, so there must be a valid use case. What is it?

2 Answers
Related