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 ByVal
Public Sub SomeMethod(ByVal argument As someclass)
then you can pass a variant;
SomeMethod var
This works because the ByVal argument is received as a local copy of a reference to a Variant[someclass] which means VB can freely perform a type-conversion (to convert the Variant[someclass]->someclass). 
It wont work when passed as ByRef because any changes to argument would also affect the calling object reference variable outside the current procedure.
If you pass As Object you don't need the ByVal. 
If your doing this a lot with custom classes VBA supports interfaces; function foo(obj as IOneOfMyWidgets)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With