向類新增屬性
Property
過程是一系列語句,用於檢索或修改模組上的自定義屬性。
有三種型別的屬性訪問器:
- 返回屬性值的
Get
過程。 Let
過程,為物件分配(非Object
)值。- 一個
Set
程式,分配Object
參考。
屬性訪問器通常成對定義,每個屬性使用 Get
和 Let
/ Set
。僅具有 Get
過程的屬性將是隻讀的,而僅具有 Let
/ Set
過程的屬性將是隻寫的。
在以下示例中,為 DateRange
類定義了四個屬性訪問器:
StartDate
( 讀/寫 )。表示範圍中較早日期的日期值。每個過程都使用模組變數mStartDate
的值。EndDate
( 讀/寫 )。表示範圍中較晚日期的日期值。每個過程都使用模組變數mEndDate
的值。DaysBetween
( 只讀 )。計算的整數值,表示兩個日期之間的天數。因為只有Get
過程,所以不能直接修改此屬性。RangeToCopy
( 只寫 )。Set
過程用於複製現有DateRange
物件的值。
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