2015-10-01 82 views
0

如何級聯自定義類的方法?訪問VBA級聯方法

我工作的是一個自定義類來處理日期。

我將類作爲屬性提供日期。然後我想根據相關的方法返回日期。例如:

InputDate.AdjustToFirst 

所以如果我輸入2015年5月15日上述將返回5/1/2015。

同樣我可以這樣做:

InputDate.AdjustToFirst.ReduceOneYear 

因此,如果輸入2015年5月15日返回將是2014年5月1日。

而且

InputDate.ReduceOneYear 

2015年5月15日將返回2014年5月15日。

我知道DateSerial,我只是想學習如何做到上述。這個想法類似於VBs variable.ToString方法。

+0

這通常稱爲方法鏈,並通過返回要麼成爲可能作爲任何實例方法的結果,您的類的當前實例或新實例(具有預期的內部狀態)。 – Phylogenesis

回答

3

您可以讓該函數簡單地返回一個新對象(method chaining已被Fred Wilson提及)。這裏一類的小例子,我叫MyDate

Private m_date As Date 

Public Sub Init(ByVal d As Date) 
m_date = d 
End Sub 

Public Function ToString() As String 
ToString = m_date 
End Function 

Public Function AddYear(y As Integer) As MyDate 
Dim newDate As MyDate 
Set newDate = New MyDate 
newDate.Init (DateAdd("yyyy", y, m_date)) 
Set AddYear = newDate 
End Function 

Public Function AddMonth(m As Integer) As MyDate 
Dim newDate As MyDate 
Set newDate = New MyDate 
newDate.Init (DateAdd("m", m, m_date)) 
Set AddMonth = newDate 
End Function 

現在你可以使用AddYearAddMonth作爲鏈功能:

Dim d As MyDate 
Set d = New MyDate 
d.Init (Now) 
MsgBox d.AddYear(2).AddMonth(4).ToString() 
+0

我想我終於明白了。我缺少的是你在這裏展示的ToString方法。如果方法返回一個類,我很難弄清楚如何獲取數據。現在我明白了。現在讓洪水門打開。 –