Объявление констант vba excel

Return to VBA Code Examples

In this Article

  • What is a Constant
  • Data Types used by Constants
  • Declaring a Constant within a Procedure
  • Declaring a Constant within a Module
  • Declaring Constants at a Global Level

This tutorial will demonstrate the use of VBA Constants.

A constant is similar to a variable and is declared in a similar way.  There is, however, a major difference between them!

VBA Constants Intro

What is a Constant

A constant is a value that we declare in our code and consequently it is reserved in our computer’s memory and stored. We have to name our constant and it’s good practice to declare the data type of our constant. When we declare the data type, we are telling the program what type of data needs to be stored by our constant .

We will use the constant in our code, and the program will also access our constant. Unlike a variable, where the actual value can change while the code is running, a constant value never changes.

Data Types used by Constants

Constants use the same data type as Variables.   The most common data types for Constants are as follows:

String – this is used to store text values.
Boolean – this is used to store TRUE or FALSE values.
Integer – this is used to store whole number values.
Double – this is used to store numbers with decimals.
Date – this is used to store dates.

To see a complete list of all data types used by Variables and Constants in VBA, click here.

In VBA, we have to use a Const statement in order to declare a Constant.  We can declare constants in a similar way to declaring Variables – at Procedure Level, at Module Level and at a Global Level.

Declaring a Constant within a Procedure

To declare a Constant at Procedure level, we declare it inside the procedure.

Sub CompanyDetails()
   Const strCompany As String = "ABC Suppliers"
   Const strAddress As String = "213 Oak Lane, Highgate"
   MsgBox strCompany & vbCrLf & strAddress
End Sub

When we run the code, the message box will return the constant values.

VBA Constants ProcedureLevel

Because the Constant is declared at Procedure level, we  can declare a Constant with the same name in a different Procedure.

VBA Constants Duplicate Contants

If we run the second Procedure, the Constant value stored in that Procedure is returned.

VBA Constants MsgBox

Declaring a Constant within a Module

If we want a Constant value to be available to all Procedures within a Module, we need to declare the constant at Module level.

VBA Constants Module Constants

This will make the same constant available to multiple procedures WITHIN that module only.

VBA Constants Constants Repeated

Should you use the Constant in a different module, an error will occur.

VBA Constants Module Error

Declaring Constants at a Global Level

You can declare Constants at a Global Level which would then mean you can use them in all the Modules contained in your entire VBA Project.

To declare a Constant as a Global Constant, we need to put the word PUBLIC in front of the declaration statement.

For example:

Public Const strCompany as string = "ABC Suppliers"

This will allow the Constant to be used in all the modules regardless of where is is declared.

VBA Constants Public Constants

NOTE: you can ONLY declare a public constant at a Module level, you CANNOT declare a public constant within a procedure.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

There can be situations when you want to declare a number in your program that you never want to be changed. In other situations, like, as if you have used a person’s name many times in your program and you want to change that name, this assigned task could be hectic if you change the name of that person at every single position you have used in your program, but, if you know constants then this task could be completed within seconds with the help of constants. In this article, you will learn how to use constants in excel VBA.

Constants in VBA

Constant is a convenient label for which value doesn’t change. Many times you have come across the constants in VBA unknowingly. A major difference between a variable and a constant is that you cannot reassign the value of a constant. For example, if you want to change the color of the cell to read, then you might use VbRed in your VBA macro.

Using constants in your code

  1. Constants help in writing defensive code so that one cannot change the value of that constant in the future. Consider a situation where you have created a module declaring all the constants and password-protected it. The scope of the constants is workbook level. Another person working in some other module cannot access the constants, thus not changing its value.
  2. Creating constants makes code more readable. For example, every person might not know what is 9.8 until mentioned its value of acceleration due to gravity.
  3. Constants save your time. Consider a situation you have used someone’s name in the code, and now you want to change it. Changing the name at every position is time taking. You can use constants by which changing the name of that person at the time of constant declaration will change the name in the entire code.

Constants can be of two types

  1. Built-In Constants
  2. User-Defined Constants

Built-In Constants

VBA provides 100+ in-built constants to VBA users. There are boolean, color, and date-type-based constants in VBA. For example, vbRed, vbBoolean, and vbDate. For example, given the cell value of C2 as “Arushi practices dsa on geeks for geeks”. Your task is to change the color of the cell to black and set the font as green using in-built VBA constants.

C2-cell-value-filled

Step 1: Open your VBA editor. The name of the procedure is geeks(). Set the color of cell C2 to black. Here, we have used the in-built constant vbBlack to color the cell. The function used to achieve this is Range(cell).Interior.Color.

Using-in-built-constant-vbBlack

Step 2: Set the font of the text inside C2 to green by using the VBgreen in-built constant. The function used to achieve this is Range(cell).Font.Color.

Using-vbGreen-in-built-constant

Step 3: Run your macro. The text color is changed to green and the background color to black.

Running-macro

Internal Working of Constants

From the above example, it might seem that the constant vbGreen changes your text color green, but that’s the half-truth. In reality, the majority of constants are numeric values. The numeric value of vbGreen is 65280. Different Methods to know the numeric value of the constant:

Method 1: Use F8

Step 1: Open your VBA editor. Under a sub procedure. Press Fn + F8, on your keyboard. Now, a yellow line may highlight the subprocedure i.e., geeks().

Highlighting-in-yellow

Step 2: Now, if your hover your cursor on the constant, it will show the numeric value of that constant. For example, the numeric value of vbGreen is 65280.

Numeric-value-of-vbGreen

Method 2: Use print in VBA

You can print the numeric value of the constant in the immediate window itself.

Step 1: Use Debug.Print(constant) in the code. Click on the run.

Printing-numeric-value

Step 2: The value of the constant will be printed in the immediate window.

Value-printed-in-immediate-window

Getting a List of built-in Constants

VBA provides a detailed list of in-built constants. You can access the name and numeric value by referring to the list.

Step 1: Open your VBA code editor. Click on the View Tab.

Clicking-view

Step 2: Click on the Object Browser or press F2.

Clicking-object-browser

Step 3: A section named Members of ‘<globals>’ is opened. Here we have the list of all the constants in VBA.

List-of-constants-in-VBA

Step 4: Click on any of the cells to get the numeric value of that constant.

Obtaining-numeric-value-of-cells

User-Defined Constants

You can get into situations when you want to define your custom constants. For example, the mathematical constants like PI(3.14), h(plank’s constant = 6.626 times 10^{-34}) etc. Here, you will require the knowledge of user-defined constants.

Converting RGB colors to a numeric value

Before learning how to declare constants in VBA, you need to know how to convert an RGB number to its numeric value. This will be helpful to know which numeric value we have to assign our constant to achieve the specified color. For example, find the numeric value of the custom black color.

Step 1: Go to the Home tab. Under the Font section, click on the theme color. Now, click on More colors.

Clicking-theme-color

Step 2: A colors tab is open. Select the custom menu. You can see the value of R, G, and B, i.e., 7, 36, and 2. Click Ok.

Selecting-custom-menu

Step 3: Now, open your VBA editor. In the immediate window, type the ?RGB(red_value, green_value, blue_value). Press Enter. You will obtain the numeric value of that color i.e., 140295.

Obtaining-numeric-value-of-that-color

Declaring Custom Constants in VBA

The custom constants are declared the same way as variables are declared, but instead of using the ‘Dim’ keyword, we use the ‘Const’ keyword in the syntax.

Syntax: Const constant_name as data_type = value_assigned

For example, given the cell value of C2 as “Arushi practices dsa on geeks for geeks”. Your task is to change the color of the cell to black and set the font as green using custom VBA constants.

Changing-color-in-cell

Step 1: Declare the constant black in the sub-procedure scope. As the numeric value of black is 0. So the constant is set to 0.

Constant-set-is-0

Step 2: Set the color of the cell to black by using Range(cell).Interior.Color function, assigned by a constant to black.

Assigning-constant-to-black

Step 3: Repeat steps 1 and 2. Declare the numeric value of green, i.e., 65280, which can be found by rgb to the numeric converter as shown above. Set the font color by Range(cell).Font.Color function, assigned by constant to green.

Declaring-custom-constant

Step 4: The background of cell C2 is set to black and the font color to green.

Cell-color-set-black-and-font-green

Scope of Constants in VBA

The constants are declared according to their scopes. Some constants have only sub-procedure scope; some might have module scope etc.

  • Scope in a procedure

The constant declared in a procedure has its scope within the procedure itself. The constant black declared inside the procedure geek() will not work for any other procedure or module.

Declaring-custom-constant-for-black-color

  • Scope in a module

The constant is declared outside a procedure, and the scope of the constant is valid for the entire module. That constant can be used in any procedure or sub-procedure, or function.

Scope-in-a-module

  • Scope in all modules

The scope of the module can be increased to all the modules by using the keyword public while declaring the constant. Now, the scope of constant is for all the modules.

Scope-in-all-modules

Home / VBA / VBA Constants

What is a Constant in VBA?

In VBA, a constant is a storage box that is itself stored in your system and it can store a value in it for you, but the value which you assign to it cannot be changed during the execution of the code. In VBA there are two different kinds of constants that you can use:

  • Intrinsic Constants
  • User-Defined Constants

Intrinsic constants are those which are built into the VBA language itself (for example, the built-in constant vbOKCancel which you use in the message box), and on the other hand, user-defined constants are those which you can create by assigning a value to it.

Declare a Constant in VBA

  1. Use the keyword “Const”.
  2. Specify a name for the constant.
  3. Use the keyword “As” after the name.
  4. Specify the “Data Type” for the constant according to the value you want to assign to it.
  5. Equals to “=” sign.
  6. In the end, the value you want to assign to it.
declare-a-constant-in-vba

Above is a constant that stores a birthdate. Now if you think, a birth date is something that is supposed to be fixed and for this kind of value, you can use a constant.

Scope of a Constant

Constant has the same scope as variables. When you declare a constant, it has a procedure-level scope, which means you can use it anywhere within the procedure. But you can declare a constant using a private or public scope.

A private constant is available only to the procedure where it is declared as a constant. To declare a private constant, you need to use the keywords “Private”, just like the following example.

Private Const iName As String = “Puneet”

And in the same way, you need to use the keyword “Public” when you need to declare a constant as public.

Public Const iPrice As String = “$3.99”

В VBA, как и в любом другом языке программирования, переменные и константы используются для хранения каких-либо значений. Как и следует из названия, переменные могут изменяться, константы же хранят фиксированные значения.

Например, константа Pi хранит значение 3,14159265… Число «Пи» не будет изменяться в ходе выполнения программы, но все же хранить такое значение удобнее как константу.

В то же время мы можем использовать переменную sVAT_Rate для хранения ставки НДС на покупаемые товары. Величина переменной sVAT_Rate может изменяться в зависимости от того, что за товар приобретается.

Содержание

  1. Типы данных
  2. Объявление переменных и констант
  3. Option Explicit
  4. Область действия переменных и констант

Типы данных

Все переменные и константы относятся к определённому типу данных. В таблице ниже приведены типы данных, используемые в VBA, с описанием и диапазоном возможных значений:

Тип данных Размер Описание Диапазон значений
Byte 1 байт Положительные целые числа; часто используется для двоичных данных от 0 до 255
Boolean 2 байта Может принимать значения либо True, либо False True или False
Integer 2 байта Целые числа (нет дробной части) от -32 768 до +32 767
Long 4 байта Большие целые числа (нет дробной части) от -2 147 483 648 до +2 147 483 647
Single 4 байта Число с плавающей точкой одинарной точности от -3.4e38 до +3.4e38
Double 8 байт Число с плавающей точкой двойной точности от -1.8e308 до +1.8e308
Currency 8 байт Число с плавающей точкой, с фиксированным количеством десятичных разрядов от -922 337 203 685 477.5808 до +922 337 203 685 477.5807
Date 8 байт Дата и время – данные типа Date представлены числом с плавающей точкой. Целая часть этого числа выражает дату, а дробная часть – время от 1 Января 100 до 31 Декабря 9999
Object 4 байта Ссылка на объект Любая ссылка на объект
String изменяется Набор символов. Тип String может иметь фиксированную или изменяющуюся длину. Чаще используется с изменяющейся длиной Фиксированной длины — приблизительно до 65 500 символов. Переменной длины — приблизительно до 2 миллиардов символов
Variant изменяется Может содержать дату, число с плавающей точкой или строку символов. Этот тип используют в тех случаях, когда заранее не известно, какой именно тип данных будет введён Число – Double, строка – String

Очевидно, что пользуясь приведённой выше таблицей и правильно выбирая тип данных, можно использовать память более экономно (например, выбрать тип данных Integer вместо Long или Single вместо Double). Однако, используя более компактные типы данных, нужно внимательно следить за тем, чтобы в коде не было попыток уместить в них не соразмерно большие значения.

Объявление переменных и констант

Примечание переводчика: Говоря о переменных в VBA, стоит упомянуть ещё один очень важный момент. Если мы объявляем переменную, но не присваиваем ей какое-либо значение, то она инициализируется значением по умолчанию:
• текстовые строки — инициализируются пустыми строками;
• числа — значением 0;
• переменные типа Boolean — False;
• даты — 30 декабря 1899.

Прежде чем использовать переменную или константу, её нужно объявить. Для этого в макрос добавляют вот такую простую строку кода:

Dim Имя_Переменной As Тип_Данных

В показанной выше строке кода Имя_Переменной – это имя переменной, которая будет использована в коде, а Тип_Данных – это один из типов данных из таблицы, приведённой чуть ранее в этой статье. Например:

Dim sVAT_Rate As Single
Dim i As Integer

Аналогично объявляются константы, но при объявлении констант обязательно сразу указывается их значение. Например, вот так:

Const iMaxCount = 5000
Const iMaxScore = 100

Объявлять переменные в Excel не обязательно. По умолчанию все введённые, но не объявленные переменные в Excel будут иметь тип Variant и смогут принять как числовое, так и текстовое значение.

Таким образом, программист в любой момент сможет использовать новую переменную (даже если она не была объявлена), и Excel будет рассматривать её как переменную типа Variant. Однако, есть несколько причин, почему так поступать не следует:

  1. Использование памяти и скорость вычислений. Если не объявлять переменную с указанием типа данных, то по умолчанию для неё будет установлен тип Variant. Этот тип данных использует больше памяти, чем другие типы данных.Казалось бы, несколько лишних байт на каждую переменную – не так уж много, но на практике в создаваемых программах могут быть тысячи переменных (особенно при работе с массивами). Поэтому излишняя память, используемая переменными типа Variant, по сравнению с переменными типа Integer или Single, может сложится в значительную сумму.К тому же, операции с переменными типа Variant выполняются гораздо медленнее, чем с переменными других типов, соответственно лишняя тысяча переменных типа Variant может значительно замедлить вычисления.
  2. Профилактика опечаток в именах переменных. Если все переменные объявляются, то можно использовать оператор VBA — Option Explicit (о нём расскажем далее), чтобы выявить все не объявленные переменные.Таким образом исключается появление в программе ошибки в результате не верно записанного имени переменной. Например, используя в коде переменную с именем sVAT_Rate, можно допустить опечатку и, присваивая значение этой переменной, записать: «VATRate = 0,175». Ожидается, что с этого момента, переменная sVAT_Rate должна содержать значение 0,175 – но, конечно же, этого не происходит. Если же включен режим обязательного объявления всех используемых переменных, то компилятор VBA сразу же укажет на ошибку, так как не найдёт переменную VATRate среди объявленных.
  3. Выделение значений, не соответствующих объявленному типу переменной. Если объявить переменную определённого типа и попытаться присвоить ей данные другого типа, то появится ошибка, не исправив которую, можно получить сбой в работе программы.На первый взгляд, это может показаться хорошей причиной, чтобы не объявлять переменные, но на самом деле, чем раньше выяснится, что одна из переменных получила не те данные, которые должна была получить – тем лучше! Иначе, если программа продолжит работу, результаты могут оказаться неверными и неожиданными, а найти причину ошибок будет гораздо сложнее.Возможно также, что макрос будет «успешно» выполнен. В результате ошибка останется незамеченной и работа продолжится с неверными данными!

В связи с этим, неверный тип данных желательно обнаруживать и как можно раньше исправлять такие ошибки в коде. По этим причинам при написании макроса VBA рекомендуется объявлять все переменные.

Option Explicit

Оператор Option Explicit заставляет объявлять все переменные, которые будут использованы в коде VBA, и при компиляции выделяет все не объявленные переменные как ошибки (прежде чем будет запущено выполнение кода). Применить этот оператор не сложно – просто запишите в самом верху файла VBA такую строку:

Option Explicit

Если хотите всегда вставлять Option Explicit в начало каждого нового созданного модуля VBA, то это можно делать автоматически. Для этого необходимо включить параметр Require Variable Declaration в настройках редактора VBA.

Это делается так:

  • В меню редактора Visual Basic нажмите Tools > Options
  • В появившемся диалоговом окне откройте вкладку Editor
  • Отметьте галочкой параметр Require Variable Declaration и нажмите ОК

При включенном параметре строка Option Explicit будет автоматически вставляться в начало каждого нового созданного модуля.

Область действия переменных и констант

Каждая объявленная переменная или константа имеет свою ограниченную область действия, то есть ограниченную часть программы, в которой эта переменная существует. Область действия зависит от того, где было сделано объявление переменной или константы. Возьмём, к примеру, переменную sVAT_Rate, которая используется в функции Total_Cost. В следующей таблице рассмотрены два варианта области действия переменной sVAT_Rate, объявленной в двух различных позициях в модуле:

Option Explicit

Dim sVAT_Rate As Single

Function Total_Cost() As Double


...


End Function
Если переменная sVAT_Rate объявлена в самом начале модуля, то областью действия этой переменной будет весь модуль (т.е. переменная sVAT_Rate будет распознаваться всеми процедурами в этом модуле).

Следовательно, если в функции Total_Cost переменной sVAT_Rate будет присвоено некоторое значение, то следующая функция, выполняемая в пределах этого же модуля, будет использовать переменную sVAT_Rate с этим же значением.

Однако, если будет вызвана какая-то функция, расположенная в другом модуле, то для неё переменная sVAT_Rate будет не известна.

Option Explicit

Function Total_Cost() As Double

Dim sVAT_Rate As Single


...


End Function
Если переменная sVAT_Rate объявлена в начале функции Total_Cost, то её область действия будет ограничена только этой функцией (т.е. в пределах функции Total_Cost, можно будет использовать переменную sVAT_Rate, а за её пределами – нет).

При попытке использовать sVAT_Rate в другой процедуре, компилятор VBA сообщит об ошибке, так как эта переменная не была объявлена за пределами функции Total_Cost (при условии, что использован оператор Option Explicit).

В показанном выше примере переменная объявлена на уровне модуля при помощи ключевого слова Dim. Однако, бывает необходимо, чтобы объявленными переменными можно было пользоваться в других модулях. В таких случаях для объявления переменной вместо ключевого слова Dim нужно использовать ключевое слово Public.

Кстати, для того, чтобы объявить переменную на уровне модуля, вместо ключевого слова Dim можно использовать ключевое слово Private, которое укажет на то, что данная переменная предназначена для использования только в текущем модуле.

Для объявления констант также можно использовать ключевые слова Public и Private, но не вместо ключевого слова Const, а вместе с ним.

В следующих примерах показано использование ключевых слов Public и Private в применении к переменным и к константам.

Option Explicit

Public sVAT_Rate As Single

Public Const iMax_Count = 5000

...

В этом примере ключевое слово Public использовано для объявления переменной sVAT_Rate и константы iMax_Count. Областью действия объявленных таким образом элементов будет весь текущий проект.

Это значит, что sVAT_Rate и iMax_Count будут доступны в любом модуле проекта.

Option Explicit

Private sVAT_Rate As Single

Private Const iMax_Count = 5000

...

В этом примере для объявления переменной sVAT_Rate и константы iMax_Count использовано ключевое слово Private. Областью действия этих элементов является текущий модуль.

Это значит, что sVAT_Rate и iMax_Count будут доступны во всех процедурах текущего модуля, но не будут доступны для процедур, находящихся в других модулях.

Оцените качество статьи. Нам важно ваше мнение:

What is VBA Const (Constants)?

Variables are the heart and soul of any programming language. We have never seen a coder or developer who does not rely on variables in their project or program. As a coder, no one is not different from others. We use variables 99% of the time. We all use the “Dim” statement; we declare VBA variablesVariable declaration is necessary in VBA to define a variable for a specific data type so that it can hold values; any variable that is not defined in VBA cannot hold values.read more. Our articles have shown you about declaring variables through the “Dim” statement. But we declare variables using another way as well. This article will show you the alternative route of declaring variables, i.e., the “VBA Constant” method.

“Const” stands for “Constants” in VBA. Using the VBA “Const” word, we can declare variables like how we declare variables using the “Dim” keyword. We can display this variable at the top of the module, between the module, in any subroutine in VBASUB in VBA is a procedure which contains all the code which automatically gives the statement of end sub and the middle portion is used for coding. Sub statement can be both public and private and the name of the subprocedure is mandatory in VBA.read more and function procedure, and the class module.

To declare the variable, we need to use the word “Const” to display the constant value. Once the variable is declared and assigned a cost, we cannot change the weight throughout the script.

Table of contents
  • What is VBA Const (Constants)?
    • Syntax of Const Statement in VBA
    • Condition of Constants in VBA
    • Examples of Const Statement in VBA
    • Make Constants Available Across Modules
    • Difference Between VBA Dim Statement & Const Statement
    • Recommended Articles

VBA-Constants

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Const (wallstreetmojo.com)

Syntax of Const Statement in VBA

The Const statement is slightly different from the “Dim” statement. To understand it better, let us look at the well-written syntax of the VBA Const statement.

Const [Variable Name] As [Data Type] = [Variable Value]

  • Const: With this word, we initialize the process of declaring the constants.
  • Variable Name: This is as usual as naming the variable. We rather call it Const Name instead of Variable Name.
  • Data Type: What kind of value our declared variable is going to hold.
  • Variable Name: Next and final part is what is the value we are going to assign to the variable we have declared. The given weight should be as per the data type.

Condition of Constants in VBA

  • The name of the constant we are declaring can contain a maximum of 256 characters in length.
  • The constant’s name cannot start with a number; rather, it should begin with the alphabet.
  • We cannot VBA reserved keywords to declare the constants.
  • The constant name should not contain any space or special characters except the underscore character.
  • One can declare multiple constants with a single statement.

Examples of Const Statement in VBA

Let’s declare your first variable through the VBA Const statement. After that, we can declare constants at the subprocedure, module, and project levels.

Now, look at how to declare at the sub procedure level.

VBA Const Example 1

In the above example, we declared constant “k” inside the sub procedure named Const_Example1(). And we have assigned the value as 75.

Now, look at the module level Constant declaration.

Example 1-1

At the top of the module, we have declared three constants in the module “Module 1”.

These VBA constants can be accessed in “Module 1” at any sub procedures within this module, i.e., “Module 1.”

Make Constants Available Across Modules

We can access those constants within the module with all the subprocedures when we declare the constants at the top of the VBA class moduleUsers have the ability to construct their own VBA Objects in VBA Class Modules. The objects created in this module can be used in any VBA project.read more.

But how can we make them available with all the modules in the workbook?

To make them available across modules, we need to declare them with the word “Public.”

Example 2

Now, the above variable is not only available with “Module 1.” Instead, we can use “Module 2” as well.

Difference Between VBA Dim Statement & Const Statement

It would help if you doubted the difference between the traditional “Dim” statement and the new “Const” statement in VBA.

We have one difference with these, i.e., look at the below image.

Dim & Const Statement Differences

Dim & Const Statement Differences 1

In the first image, as soon as we declare a variable, we have assigned some values to them.

But in the second image, using the “Dim” statement first, we have declared variables.

After declaring a variable, we have assigned values separately in the different lines.

Like this, we can use the VBA “Const” statement to declare constants, which is a similar way of communicating variables with the “Dim” statement.

Recommended Articles

This article has been a guide to VBA Const (Constants). Here we discuss how to use the Constant statement in VBA along with examples and its critical differences with Dim information. Below are some useful Excel articles related to VBA: –

  • VBA Do Loop
  • VBA DoEvents
  • VBA Option Explicit
  • VBA Text

Понравилась статья? Поделить с друзьями:
  • Объемный график в excel по данным таблицы
  • Объявление компьютерный мастер образец word
  • Объемные формулы в excel
  • Объявление компьютерного мастера образец word
  • Объемные фигуры для word