VBA Creating a Custom Class Adding a Property to a Class


Example

A Property procedure is a series of statement that retrieves or modifies a custom property on a module.

There are three types of property accessors:

  1. A Get procedure that returns the value of a property.
  2. A Let procedure that assigns a (non-Object) value to an object.
  3. A Set procedure that assigns an Object reference.

Property accessors are often defined in pairs, using both a Get and Let/Set for each property. A property with only a Get procedure would be read-only, while a property with only a Let/Set procedure would be write-only.

In the following example, four property accessors are defined for the DateRange class:

  1. StartDate (read/write). Date value representing the earlier date in a range. Each procedure uses the value of the module variable, mStartDate.
  2. EndDate (read/write). Date value representing the later date in a range. Each procedure uses the value of the module variable, mEndDate.
  3. DaysBetween (read-only). Calculated Integer value representing the number of days between the two dates. Because there is only a Get procedure, this property cannot be modified directly.
  4. RangeToCopy (write-only). A Set procedure used to copy the values of an existing DateRange object.
Private mStartDate As Date                ' Module variable to hold the starting date
Private mEndDate As Date                  ' Module variable to hold the ending date
  
' Return the current value of the starting date
Public Property Get StartDate() As Date
    StartDate = mStartDate
End Property

' Set the starting date value. Note that two methods have the name StartDate
Public Property Let StartDate(ByVal NewValue As Date)
    mStartDate = NewValue
End Property
  
' Same thing, but for the ending date
Public Property Get EndDate() As Date
    EndDate = mEndDate
End Property
  
Public Property Let EndDate(ByVal NewValue As Date)
    mEndDate = NewValue
End Property

' Read-only property that returns the number of days between the two dates
Public Property Get DaysBetween() As Integer
    DaysBetween = DateDiff("d", mStartDate, mEndDate)
End Function

' Write-only property that passes an object reference of a range to clone
Public Property Set RangeToCopy(ByRef ExistingRange As DateRange)

Me.StartDate = ExistingRange.StartDate
Me.EndDate = ExistingRange.EndDate

End Property