I’ve got a “compilation” error in Excel VBA, which I don’t understand…
I’ve got a method like that :
Public Sub SomeMethod(ByRef argument As SomeClass)
... <- 'argument' must be called ByRef because I have to modify it
End Sub
If I define a variable like :
Dim var As SomeClass
No problem, I can call :
SomeMethod var
and it’s working.
BUT, if I define a Variant variable like :
Dim var as Variant
Set var = New SomeClass
It doesn’t work.
If I call :
SomeMethod var
VB pops-up a message : ‘ByRef argument type mismatch’
If I call :
SomeMethod (var)
it “compiles”, but var is then passed ByVar and it gave me a runtime-error message : ‘Object doesn’t support this property or method’
So I basically just want to tell VBA that my Variant variable ‘var’ is in fact a ‘SomeClass’ object (in debugger, VBA says so), but I don’t know how to do that…
Could someone please help me ?
Decorate the argument with
ByValthen you can pass a variant;
This works because the
ByVal argumentis received as a local copy of a reference to aVariant[someclass]which means VB can freely perform a type-conversion (to convert theVariant[someclass]->someclass).It wont work when passed as
ByRefbecause any changes toargumentwould also affect the calling object reference variable outside the current procedure.If you pass
As Objectyou don’t need theByVal.If your doing this a lot with custom classes VBA supports interfaces;
function foo(obj as IOneOfMyWidgets)