|
MajP (TechnicalUser) |
31 Jul 12 15:39 |
Example
I have an external project in an Access db called "dbDummyClass". The class is called "DummyClass".
CODE'Class DummyClass in database dbDummyClass
Option Compare Database
Option Explicit
Private mName As String
Private mWeight As Double
Private mShipDate As Date
Const minWeight = 0.25
'custom event
Event NameChange(NewName As String, OldName As String)
Private Sub Class_Initialize()
'Initialize and terminate are the only events that a class has
'Unfortunately you cannot pass in parameters.
'But you could hard code some defaults
mName = "Not Assigned"
mWeight = minWeight
mShipDate = Now
End Sub
Public Sub MyClassInitialize(theName As String, theWeight As Double, theShipDate As Date)
'So fake it with your own initialize procedure
mName = theName
mWeight = theWeight
mShipDate = theShipDate
End Sub
Public Property Get Name() As String
Name = mName
End Property
Public Property Let Name(ByVal theName As String)
'This would be a Set if assigning to an object
'Here is also the custom event
RaiseEvent NameChange(theName, mName)
mName = theName
End Property
Public Sub PrintObjectInfo()
Dim strInfo As String
'I can use the property here
strInfo = "Name: " & Me.Name
'I did not make a property for weight, I use the public variable
strInfo = strInfo & vbCrLf & "Weight: " & mWeight
strInfo = strInfo & vbCrLf & "ShipDate: " & mShipDate
Debug.Print strInfo
End Sub
Private Sub Class_Terminate()
'Initialize and terminate are the only events that a class has
'Do clean up here if necessary
End Sub
In this external project is also have a standard module, in which I have a function that allows me to instantiate a new DummyClass instance and return it.
CODEPublic Function NewDummy(Optional theName As String = "No Name", Optional theWeight As Double = 12.5, Optional theShipDate As Variant = Null) As DummyClass
If Not IsDate(theShipDate) Then theShipDate = Now
Set NewDummy = New DummyClass
NewDummy.MyClassInitialize theName, theWeight, CDate(theShipDate)
End Function
To use this class from my current project
CODEPublic Sub TestExternal()
Dim dcDummy As Object
Set dcDummy = newdummy("Test", 123, Now)
dcDummy.printobjectinfo
End Sub
The results in the immediate window are
Name: Test
Weight: 123
ShipDate: 7/31/2012 3:30:44 PM
Unfortunately I believe this is how it has to be done if VBA. You lose all intellisense for the object. |
|