
VBA
CallByName(Object, ProcName, CallType, Arguments...)
- Object: The object on which the property, method, or function is being called.
- ProcName: A string expression that contains the name of the property, method, or function on the object.
- CallType: A constant that specifies the type of procedure being called. It can be one of the following: VbGet, VbLet, VbMethod, VbSet.
- VbGet is used to retrieve the value of a property.
- VbLet and VbSet are used to assign a value to a property (with VbLet for value properties and VbSet for object properties).
- VbMethod is used to call a method.
- Arguments…: Optional parameters that are passed to the property, method, or function being called.
Example Usage
Suppose you have a class named MyClass with a method ShowMessage and a property MyProperty. Here’s how you might use CallByName:VBA
In this example:
Dim obj As MyClass
Set obj = New MyClass
' Call a method
CallByName obj, "ShowMessage", VbMethod
' Set a property
CallByName obj, "MyProperty", VbLet, "New Value"
' Get a property
Dim propValue As String
propValue = CallByName(obj, "MyProperty", VbGet)
- The ShowMessage method of obj (an instance of MyClass) is called.
- The MyProperty property of obj is set to “New Value”.
- The value of MyProperty is retrieved and stored in propValue.
Points to Remember
- CallByName is very useful for calling methods or properties dynamically when the exact names are not known until runtime.
- It’s important to ensure that the ProcName string matches the actual name of the method or property on the object. Mismatches will result in runtime errors.
- This function is commonly used in situations where the code needs to be flexible and able to work with different objects or classes.