VBA Constant Basic Tutorial

Date:2020-11-18 Author:Sandra

VBA constants are relative to the concept of VBA variables. Unlike variables, once a constant is assigned, its value cannot be changed. During the entire process of the program, its value remains unchanged. If new data is assigned forcibly, VBA will report an error. Using VBA constants can make a value expressed in a more convenient way and improve programming efficiency. For example, use Pi to represent “3.14159…”, and use Pi to represent the π value directly in the code.

Declare Constant

Declaring a constant is similar to declaring a variable, you need to specify the name and data type. The difference is that the value of a constant needs to be specified when it is declared.

The syntax for declaring constants is as follows:

VBA Constant Basic Tutorial

Naming Rules

Same as variables, constant naming must meet the following conditions, otherwise the program will go wrong.

  • The first letter must start with a letter.
  • Cannot contain spaces,. (Period),! (Exclamation mark), @, &, $, # and other characters.
  • The length cannot exceed 255 characters.
  • You cannot use keywords saved in VBA as variable names.

Constant Type

The constant type is the same as the variable type. For specific information, please refer to the previous tutorial.

Now, Let’s take a look at an example, declaring the value of π as a constant, and in the subsequent process, directly use Pi as the value of π to participate in the calculation.

VBA Constant Basic Tutorial
VBA Constant Basic Tutorial

When we enter any value as radius in cell A1, we will get the circumference of the circle by running this code.

VBA Constant Basic Tutorial
VBA Constant Basic Tutorial

In this article, we learned another basic concept in VBA, VBA constants. A constant is a constant value as opposed to a variable. In the program, you can use constants to express some complex values to simplify the code and improve efficiency.

Copyright Statement: Regarding all of the posts by this website, any copy or use shall get the written permission or authorization from Myofficetricks.

Leave a Reply

Your email address will not be published. Required fields are marked *