Keyword

Const


Description

Declares a value as a local constant.

Usage

Const name [As type] = value

Part

Type

Description

constantName

String literal

The name of the constant.

value

Any data type.

The value to assign to the constant.

Notes

The Const statement can be used in place of the Var statement followed by an assignment statement when you are sure that the value of the variable should not change within the method. Using Const instead of Var provides a convenient way to manage such values.

Constants are assigned once and can never change. Local constants are only available within the method where there are declared.

You can optionally specify a data type for the constant value.

You can use Const anywhere within the method and can also declare constants within code blocks (such a For...Next, If...Then, etc.). Constants declared within code blocks are not accessible outside the code block.

You can assign any constant expression to a constant, such as:

Const kNumber = 10 * 45
Const kString = "Bob " + "Roberts"

If you use a non-constant value in an expression for a constant, you will get the This is a constant; its value can't be changed error.


Project item constants

You can also create constants in a window, class, or module. Constants that belong to windows, web pages, views or classes can be public (accessible throughout the application), protected (accessible only within the object that owns the constant and its subclasses), or private (accessible only within the object that owns it). Modules can also have global constants, accessible throughout the application.

Sample code

Some ways to use constants:

Const kAnswer As Integer = 42
Const kPi As Double = 3.14159

// Constants declared from expressions
Const kNumber = 10 * 45 // kNumber = 450
Const kName = "Bob " + "Roberts" // kName = "Bob Roberts"

// Assign constant to a variable
Var name As String
name = kName

// Assign constant to a property
Label1.Text = kName

Compatibility

All project types on all supported operating systems.

See also

Var statement.