Declare a Default Method/Property in a Class Module
VBA does not give you a simple mechanism by which you can specify a Property to be the Default. VBA does, however, support Default Properties but you'll simply have to jump through several hoops to get there. The following steps will describe exactly how to create a Default Property in your Classes:
- Create the following simple Class named MyClass. MyClass will consist of just 2 Properties: Value (Default) and MyName. It does not contain any Methods.
Expand|Select|Wrap|Line Numbers- Private pValue As Long
- Private pMyName As String
- Property Get Value() As Variant
- Value = pValue
- End Property
- Property Let Value(ByVal vNewValue As Variant)
- pValue = vNewValue
- End Property
- Property Get MyName() As Variant
- MyName = pMyName
- End Property
- Property Let MyName(ByVal vNewName As Variant)
- pMyName = vNewName
- End Property
- Save your Class Module (MyClass) after creating it.
- From the File menu, choose Remove MyClass.
- When prompted to Export the File First, choose Yes and save the Module.
- Open the exported file (*.cls) in Notepad, or any Text Editor.
- In Notepad, find your Property Get Procedure, in this case Value. Add the following line of code on a blank line immediately following the Property Get Statement.
Expand|Select|Wrap|Line Numbers- Attribute Value.VB_UserMemId = 0
- The Property Get Procedure should now look like the following:
Expand|Select|Wrap|Line Numbers- Property Get Value() As Variant
- Attribute Value.VB_UserMemId = 0
- Value = pValue
- End Property
- Save the file in Notepad, then exit.
- In VBA choose Import File and select the file you just modified (MyClass.cls).. You will not see the 'Attribute' Statement in the VBA Editor. The Editor reads and processes Attribute Statements, but does not display them, nor does it allow them to be entered in the Editor.
- The following code block will now work where it previously would not have because Value was not the Default Property of the MyClass Object.
Expand|Select|Wrap|Line Numbers- 'Declare a Variable to refer to the New Instance of
- 'MyClass (a MyClass Object)
- Dim clsMyClass As MyClass
- 'Instantiate the Class
- Set clsMyClass = New MyClass
- 'Can do this because Value is now the Default Property
- clsMyClass = 9999
- 'Must use standard syntax since MyName is not a Default Property
- clsMyClass.MyName = "Fred Flintstone"
- MsgBox clsMyClass 'returns 9999
- MsgBox clsMyClass.MyName 'returns Fred Flintstone
- The above code has been tested and is fully operational. To the best of my knowledge, it requires Access 2000 and above to work.
- Should you have any questions feel free to ask.