常數(Const)

如果你的應用程式中的值永遠不會更改,則可以定義命名常量並使用它來代替文字值。

你只能在模組或過程級別使用 Const。這意味著變數的宣告上下文必須是類,結構,模組,過程或塊,並且不能是原始檔,名稱空間或介面。

Public Const GLOBAL_CONSTANT As String = "Project Version #1.000.000.001"
Private Const MODULE_CONSTANT As String = "Something relevant to this Module"

Public Sub ExampleDeclaration()    

    Const SOME_CONSTANT As String = "Hello World"
    
    Const PI As Double = 3.141592653

End Sub

雖然指定常量型別可以被認為是一種好的做法,但並不是嚴格要求的。不指定型別仍將導致正確的型別:

Public Const GLOBAL_CONSTANT = "Project Version #1.000.000.001" 'Still a string
Public Sub ExampleDeclaration()

    Const SOME_CONSTANT = "Hello World"           'Still a string
    Const DERIVED_CONSTANT = SOME_CONSTANT        'DERIVED_CONSTANT is also a string
    Const VAR_CONSTANT As Variant = SOME_CONSTANT 'VAR_CONSTANT is Variant/String
    
    Const PI = 3.141592653        'Still a double
    Const DERIVED_PI = PI         'DERIVED_PI is also a double
    Const VAR_PI As Variant = PI  'VAR_PI is Variant/Double
    
End Sub

請注意,這是特定於常量,而不是指定型別的變數導致 Variant 型別的變數。

雖然可以將常量顯式宣告為 String,但不可能使用固定寬度字串語法將常量宣告為字串

'This is a valid 5 character string constant
Const FOO As String = "ABCDE"

'This is not valid syntax for a 5 character string constant
Const FOO As String * 5 = "ABCDE"