常数(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"