VBA中的class是不能定義常量constants的, 對於習慣OOP的人來說,這當然會帶來不便. 但是,我們還是可以”曲綫”實現這一目的.
方法就是利用Enum.但可惜的是,該曲綫方法只支持Long類型的參數,因為Enum只支持Long類型.
更多關於Enum的信息,可參閱此文.
Option Explicit
' The following code saved in a normal module
Sub main()
Dim clsFruit As New CFruit
clsFruit.printMe
End Sub
Option Explicit
Public Enum enumFruits
banana = 5
apple = 2.5
orange
End Enum
Function printMe()
Debug.Print enumFruits.banana '5
Debug.Print enumFruits.apple 'result will still be 2, not 2.5
'3 Those constants without a value would be one more than the previous variable
Debug.Print enumFruits.orange
End Function
技術上VB根本不承認Public Enum是類的一部份
There’s no need even to instantiate the class, since technically Visual Basic doesn’t consider Public Enum as members of a class, even though they’re written to the type library.