VBA - CallByName won't accept variant arguments

后端 未结 1 1140
终归单人心
终归单人心 2021-01-29 10:28

Solution: Just put brackets around Value in the CallByName statement to force evaluation of it.

Ex. CallByName MobClass, TargetData, vbLet, (Valu

相关标签:
1条回答
  • 2021-01-29 11:19

    The Problem is that you pass the properties-arguments by reference not by value, but you can't pass a reference to a different datatype (variant -> long) as the types don't match and it can't be converted as this would change the data type in the caller too. By using brackets, you force the argument to be passed by value and it can be casted as typeLong.

    You can avoid this by using ByValin theProperty Letterinstead ofByRef(what is implicit used if not set). You are aware that by referencing a variable, changes made in the property change the callers value too?

    Example:

    Class PassExample

    'Save as class module PassExample
    Public Property Let PropByVal(ByVal NewVal As Long)
    NewVal = 1
    End Property
    Public Property Let PropByRef(ByRef NewVal As Long)
    NewVal = 1
    End Property 
    

    Module with test sub:

    'save as standard module
    Sub test()
    Dim v As Variant
    v = 0
    
    Dim ExampleInstance As New PassExample
    
    CallByName ExampleInstance, "PropByVal", VbLet, v 'this works
    CallByName ExampleInstance, "PropByRef", VbLet, v 'type mismatch
    CallByName ExampleInstance, "PropByRef", VbLet, (v) 'this works as ByRef is changed to byval
    Debug.Print v ' shows 0, not 1 as it should be if referenced
    
    CallByName ExampleInstance, "PropByRef", VbLet, CVar(v) ' works too as it passes a function-result that can't be referenced
    
    End Sub
    

    Thanks to Rory and chris neilsen for providing the solution!

    0 讨论(0)
提交回复
热议问题