(Warning: Although it might look like one at first glance, this is not a beginner-level question. If you are familiar with the phrase "Let coercion" or you have ever looked into the VBA spec, please keep on reading.)
Let's say I have an expression of type Variant
, and I want to assign it to a variable. Sounds easy, right?
Dim v As Variant
v = SomeMethod() ' SomeMethod has return type Variant
Unfortunately, if SomeMethod
returns an Object (i.e., a Variant with a VarType of vbObject), Let coercion kicks in and v
contains the "Simple data value" of the object. In other words, if SomeMethod returns a reference to a TextBox, v
will contain a string.
Obviously, the solution is to use Set
:
Dim v As Variant
Set v = SomeMethod()
This, unfortunately, fails if SomeMethod
does not return an object, e.g. a string, yielding a Type Mismatch error.
So far, the only solution I have found is:
Dim v As Variant
If IsObject(SomeMethod()) Then
Set v = SomeMethod()
Else
v = SomeMethod()
End If
which has the unfortunate side effect of calling SomeMethod
twice.
Is there a solution which does not require calling SomeMethod
twice?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…