Vba excel переменные integer

In this Article

  • Integer (Int) Variable Type
    • Long Variable Type
  • Decimal Values & Int Data Types
    • Decimal / Double Data Type
  • Declare Int Variable at Module or Global Level
    • Module Level
    • Global Level
  • Convert String to Int
  • Convert Int to String
    • Format Integer Stored as String

Integer (Int) Variable Type

The VBA Int data type is used to store whole numbers (no decimal values). However as we’ll see below, the Integer values must fall within the range ‑32768 to 32768.

To declare an Int variable, you use the Dim Statement (short for Dimension):

Dim intA as Integer

Then, to assign a value to a variable, simply use the equal sign:

intA = 30000

Putting this in a procedure looks like this:

Sub IntExample()
'declare the integer
   Dim intA as Integer
'populate the integer
   intA = 30000
'show the message box
   MsgBox intA
End Sub

If you run the code above, the following message box will be shown.

vba integer intexample msgbox

Long Variable Type

As mentioned above, Int variables can only store values between ‑32768 to 32768. If you attempt to assign a value outside that range to an Int variable you’ll receive an error:

vba integer intexample overflow error

When you click on de-bug, the code will break at the ‘populate the integer line as an integer cannot store a number as high as 50000.

vba integer intexample overflow debug

Instead, you can declare a variable with the Long data type:

Dim longA as Long

Long Variables can store very long data types (-2,147,483,648 to 2,147,483,648).

<<link to long variable article>>

Why would you use Int variables instead of Long variables?

Long variables use more memory. Years ago, memory was a big concern when writing code, however now computing technology is much improved and it’s doubtful you’ll encounter memory issues caused by long variables when writing VBA code.

We recommend always using Long variables instead of Int variables. We will continue this tutorial discussing Int variables, but keep in mind that you can use the Long variable type instead.

Decimal Values & Int Data Types

Int variables can not store decimal values. If you pass a decimal number an integer, the decimal number will be rounded to remove the decimal.

Therefore, if you were to run the procedure below:

Sub IntExampleB() 
'declare the integer
   Dim intA as Integer 
'populate the integer 
   intA = 3524.12
'show the message box 
   MsgBox intA 
End Sub

You would get the following result (rounding down):

vba integer passing decimal round down msgbox

However, this code below:

Sub IntExampleB()
 'declare the integer 
   Dim intA as Integer 
'populate the integer 
   intA = 3524.52 
'show the message box 
   MsgBox intA 
End Sub

Would return the following message box (rounding up):

vba integer passing decimal round up msgbox

Decimal / Double Data Type

If you want to store a decimal place, you would need to declare a variable that allows for decimal places.  There are 3 data types that you can use – Single, Double or Currency.

Dim sngPrice as Single
Dim dblPrice as Double
Dim curPrice as Currency

The Single data type will round the decimal point slightly differently to the double and currency data type, so it is preferable to use double to single for accuracy.  A double can have up to 12 decimal places while currency and single can both have up to 4 decimal places.

vba integer double example

For further information about these data types, you can have a look here.

Declare Int Variable at Module or Global Level

In the previous examples, we’ve declared the Int variable within a procedure. Variables declared with a procedure can only be used within that procedure.

vba integer procedure declaration

Instead, you can declare Int variables at the module or global level.

Module Level

Module level variables are declared at the top of code modules with the Dim statement.

vba integer module declaration

These variables can be used with any procedure in that code module.

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!

automacro

Learn More

Global Level

Global level variables are also declare at the top of code modules. However, instead of using the Dim statement, use the Public statement to indicate that the integer variable is available to be used throughout your VBA Project.

Public IntA as Integer

vba integer global declaration

If you were to declare the integer at a module level and then try to use it in a different module, an error would occur.

vba integer declaration notdefined

However, if you had used the Public keyword to declare the integer, the error would not occur and the procedure would run perfectly.

Convert String to Int

There might be an instance or instances when you will need to convert a number stored as a string to an integer value.

vba integer intexample string to integer immediate

You will notice in the immediate window that the integer value goes to the right indicating a number, while the string value goes to the left – indicating text.

Convert Int to String

Conversely, you can convert an integer value to a string.

vba integer intexample integer to string immediate

For further information about these data types, you can have a look here.

VBA Programming | Code Generator does work for you!

Format Integer Stored as String

<<also talk about the Format function, to assign number formatting>>

Справочная таблица по встроенным типам данных VBA Excel. Функция TypeName, возвращающая тип данных переменной. Оператор Option Explicit в начале модуля.

Встроенные типы данных

Встроенные типы данных VBA Excel:

Тип данных Байты* Диапазон значений
Byte 1 Целые числа:
от 0 до 255
Boolean 2 True (Истина) или False (Ложь)
Integer 2 Целые числа:
от -32768 до 32767
Long 4 Целые числа:
от -2147483648 до 2147483647
Single 4 Отрицательные числа:
от -3,402823Е+38 до -1,401298Е-45
Положительные числа:
от 1,401298Е-45 до 3,402823Е+38
Double 8 Отрицательные числа:
от -1,79769313486232Е+308
до -4,94065645841247Е-324
Положительные числа:
от 4,94065645841247Е-324
до 1,79769313486232Е+308
Currency 8 от -922337203685477,5808
до 922337203685477,5807
Date 8 с 1 января 100 года
по 31 декабря 9999 года
Object 4 Ссылка на объект
String
(переменной длины)
10 + длина строки от 0 до ≈2 млрд символов
String
(фиксированной длины)
длина строки от 1 до ≈65400 символов
Variant
(числа)
16 В пределах диапазона типа
данных Double
Variant
(символы)
22 + длина строки от 0 до ≈2 млрд символов

Дополнительно для VBA7:

Тип данных Байты* Диапазон значений
LongLong 8 Целые числа:
от –9 223 372 036 854 775 808
до 9 223 372 036 854 775 807
Доступен только в 64-разрядных системах.
LongPtr 4 или 8 В 32-разрядных системах соответствует типу Long:
от -2147483648 до 2147483647,
в 64-разрядных — типу LongLong:
от –9 223 372 036 854 775 808
до 9 223 372 036 854 775 807

*Резервируется память в байтах на каждую переменную соответствующего типа.

Тип данных Variant может принимать специальные значения: Empty, Error, Nothing и Null.

Кроме встроенных типов данных VBA Excel позволяет использовать пользовательские типы, создаваемые с помощью оператора Type. Диапазон значений пользовательского типа данных определяется встроенными типами, из которых он состоит.

Переменные с типами данных Byte, Boolean, Integer, Long, Single и Double можно объявлять с помощью суффиксов.

Функция TypeName

TypeName – это функция, возвращающая значение типа String с информацией о переменной.

Чаще всего, функция TypeName возвращает наименование типа данных аргумента (значения), содержащегося в переменной. Кроме наименований встроенных типов данных, функция TypeName может возвращать следующие значения:

Значение Описание
Collection, Dictionary, Range, Worksheet и т.д. Тип известного объекта, ссылка на который содержится в объектной переменной
Error Переменная содержит значение ошибки
Empty Неинициализированное значение
Null Отсутствие допустимых данных
Unknown Объект, тип которого неизвестен
Nothing Объектная переменная, которая не ссылается на объект

Если переменная объявлена с числовым типом данных или String, функция TypeName возвратит наименование этого типа данных. Если переменная объявлена с типом данных Variant или Object, возвращаемое значение будет зависеть от содержимого переменной.

Пример:

Sub Primer()

Dim a As Single, b As Date, c As Variant

    MsgBox «a As Single:  « & TypeName(a)  ‘Single

    MsgBox «b As Date:  « & TypeName(b)  ‘Date

    MsgBox «c As Variant:  « & TypeName(c)  ‘Empty (значение не инициализировано)

c = 1.236

    MsgBox «c = 1.236:  « & TypeName(c)  ‘Double

Set c = Cells(1, 1)

    MsgBox «Set c = Cells(1, 1):  « & TypeName(c)  ‘Range (тип объекта)

Set c = Worksheets(1)

    MsgBox «Set c = Worksheets(1):  « & TypeName(c)  ‘Worksheet (тип объекта)

End Sub

Оператор Option Explicit

VBA Excel допускает использование в коде как объявленных, так и необъявленных переменных. Необъявленным переменным присваивается тип данных Variant и они могут принимать все допустимые значения, свойственные этому типу.

Если при написании кода допустить ошибку в имени ранее использовавшейся переменной, компилятор зарегистрирует ее как новую. Это вызовет ошибки в работе программы, причину которых (ошибку в имени переменной) трудно обнаружить при отладке.

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

Размещается оператор Option Explicit в самом начале модуля перед всеми остальными операторами. Чтобы каждый раз не вставлять его вручную и, тем более, не забыть о нем, можно настроить редактор VBA Excel, чтобы он автоматически добавлял Option Explicit при создании нового модуля.

Настройка автоматического добавления Option Explicit

1. Откройте окно Options через вкладку меню Tools:

Путь к окну Options

2. Отметьте галочкой опцию Require Variable Declaration на вкладке Editor:

Окно Options

3. Теперь новый модуль открывается со строкой Option Explicit:

Строка Option Explicit вставлена


An integer is a data type in VBA given to any variable to hold integer values. The limitations or the bracket for the number of an integer variable can hold similar in VBA to those of other languages. Using the DIM statement or keyword in VBA, one can define any variable as an integer variable.

Excel VBA Integer

Data types are important in any coding language because all the variable declarations should follow the data type assigned to those variables. We have several data types to work with, and each data type has its advantages and disadvantages associated with it. When declaring variables, it is important to know the particular data type. We dedicate this article to the “Integer” data type in VBA. We will show you the complete picture of the “Integer” data type.

Table of contents
  • Excel VBA Integer
    • What is the Integer Data Type?
    • Examples of Excel VBA Integer Data Type
      • Example #1
      • Example #2
      • Example #3
    • Limitations of Integer Data Type in Excel VBA
    • Recommended Articles

What is the Integer Data Type?

Integers are whole numbers, which could be positive, negative, or zero but not fractional numbers. In the VBA context, “Integer” is a data type we assign to the variables. It is a numerical data type that can hold whole numbers without decimal positions. Integer data type 2 bytes of storage is half the VBA LONGLong is a data type in VBA that is used to store numeric values. We know that integers also store numeric values, but Long differs from integers in that the range for data storage is much larger in the case of long data type.read more data type, i.e., 4 bytes.

VBA Integer

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 Integer (wallstreetmojo.com)

Examples of Excel VBA Integer Data Type

Below are examples of the VBAHere’s a list of the top examples of VBA Macro code in Excel: Print All Sheet Names, Insert Different Color Index in VBA, Insert Worksheets as Much as You want, Insert Blank Row After Every Other Row
Highlight Spelling Mistakes.
read more
Integer Data type.

You can download this VBA Integer Data Type Template here – VBA Integer Data Type Template

Example #1

When we declare a variable, it is necessary to assign a data type, and an integer is one of them, which all the users commonly use based on the requirements.

As we said, an integer can only hold whole numbers, not any fractional numbers. Follow the below steps to see the example of a VBA Integer data type.

Step 1: Declare the variable as Integer.

Code:

Sub Integer_Example()

  Dim k As Integer

End Sub

VBA Integer Example 1

Step 2: Assign the value of 500 to the variable “k.”

Code:

Sub Integer_Example1()

  Dim k As Integer

  k = 500

End Sub

VBA Integer Example 1-1

Step 3: Show the value in the VBA message boxVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.

Code:

Sub Integer_Example1()

  Dim k As Integer

  k = 500

  MsgBox k

End Sub

VBA Integer Example 1-2

When we run the code using the F5 key or manually, we can see 500 in the message box.

VBA Integer Example 1-3

Example #2

Now, we will assign the value -500 to the variable “k.”

Code:

Sub Integer_Example2()

  Dim k As Integer

  k = -500

  MsgBox k

End Sub

VBA Integer Example 2

Run this code manually or press F5. Then, it will also show the value of -500 in the message box.

VBA Integer Example 2-1

Example #3

As we told VBA, the Integer data type can hold only whole numbers, not fraction numbers like 25.655 or 47.145.

However, we will try to assign the fraction number to a VBA Integer data type. For example, look at the below code.

Code:

Sub Integer_Example3()

    Dim k As Integer

    k = 85.456

    MsgBox k

End Sub

Example 3

We have assigned 85.456 to the variable “k.” Next, we will run this VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more to see the result.

VBA Integer Example 3-1

  • It returned the result as 85, even though we assigned the fraction number value since VBA roundsRound function in VBA is a mathematical function that rounds up or down the given number to the specific set of decimal places specified by the user to ease calculation.read more the fraction numbers to the nearest integer.
  • All the fraction numbers less than 0.5 will be rounded down to the nearest integer. For example 2.456 = 2, 45.475 = 45.
  • All the fraction numbers, which are greater than 0.5, will be rounded up to the nearest integer. For example 10.56 = 11, 14.789 = 15.

To look at the roundup integer lets, the value of “k” to 85.58.

Code:

Sub Integer_Example3()

    Dim k As Integer

    k = 85.58

    MsgBox k

End Sub

Example 3-2

When we run this code using the F5 key or manually, it will return 86 because it will round up anything more than 0.5 to the next integer number.

VBA Integer Example 3-3

Limitations of Integer Data Type in Excel VBA

Overflow Error: The Integer data type should work fine if the assigned value is between -32768 and 32767. The moment it crosses the limit on either side, it will cause you an error.

For example, look at the below code.

Code:

Sub Integer_Example4()

    Dim k As Integer

    k = 40000

    MsgBox k

End Sub

Example 4

We have assigned the value of 40000 to the variable “k.”

Since we have complete knowledge of Integer data types, we know it does not work because integer data types cannot hold the value of anything more than 32767.

Let us run the code manually or through the F5 key and see what happens.

VBA Integer Example 4-1

We got the error “Overflow” because the Integer data type cannot hold anything more than 32767 for positive numbers and -32768 for negative numbers.

Type Mismatch Error: Integer data can only hold numerical values between -32768 to 32767. Suppose any number assigned more than these numbers will show an Overflow errorVBA Overflow Error or «Run Time Error 6: Overflow» occurs when the user inserts a value that exceeds the capacity of a specific variable’s data type. Thus, it is an error that results from the overloading of data beyond the desired data type limit of the variable.read more.

Now, we will try to assign text or string values to it. In the below example code, we have assigned the value “Hello.”

Code:

Sub Integer_Example4()

    Dim k As Integer

    k = "Hello"

    MsgBox k

End Sub

Example 4-2

We will run this code through the run option or manually and see what happens.

VBA Integer Example 4-3

It shows the error as “Type mismatch” because we cannot assign a text value to the variable “integer data type.”

Recommended Articles

This article has been a guide to VBA Integer data type in Excel. Here, we discussed using the VBA Integer data type in Excel, its limitations, and the examples and downloadable Excel template.

  • RoundUp in VBA
  • 2 Types of Data Types in VBA
  • VBA Function IsEmpty
  • How to Use Paste Special in VBA?

Содержание

  1. Сводка типов данных
  2. Набор встроенных типов данных
  3. Преобразование между типами данных
  4. Проверка типов данных
  5. Возвращаемые значения функции CStr
  6. См. также
  7. Поддержка и обратная связь
  8. Целочисленный тип данных (Visual Basic)
  9. Комментарии
  10. Литеральные назначения
  11. Советы по программированию
  12. Диапазон
  13. Объявление переменных
  14. Оператор Public
  15. Оператор Private
  16. Оператор Static
  17. Оператор Option Explicit
  18. Объявление объектной переменной для автоматизации
  19. См. также
  20. Поддержка и обратная связь

Сводка типов данных

Тип данных — это характеристика переменной, определяющая тип содержащихся в ней данных. К типам данных относятся типы, указанные в таблице ниже, а также пользовательские типы и определенные типы объектов.

Набор встроенных типов данных

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

Тип данных Размер хранилища Диапазон
Boolean 2 байта True или False
Byte 1 байт от 0 до 255
Collection Неизвестно Неизвестно
Currency (масштабируемое целое число) 8 байт от –922 337 203 685 477,5808 до 922 337 203 685 477,5807
Date 8 байт от 1 января 100 г. до 31 декабря 9999 г.
Decimal 14 байт +/–79 228 162 514 264 337 593 543 950 335 без десятичной запятой

+/–7,9228162514264337593543950335 с 28 разрядами справа от десятичной запятой

Наименьшее ненулевое число равно +/–0,0000000000000000000000000001

Dictionary Неизвестно Неизвестно
Double (число с плавающей запятой двойной точности) 8 байт от –1,79769313486231E308 до –4,94065645841247E-324 для отрицательных значений

от 4,94065645841247E-324 до 1,79769313486232E308 для положительных значений

Integer 2 байта от –32 768 до 32 767
Long (целое число Long) 4 байта от –2 147 483 648 до 2 147 483 647
LongLong (целое число LongLong) 8 байт от –9 223 372 036 854 775 808 до 9 223 372 036 854 775 807

Действительно только для 64-разрядных платформ.

LongPtr (целое число Long в 32-разрядных системах, целое число LongLong в 64-разрядных системах) 4 байта в 32-разрядных системах

8 байт в 64-разрядных системах

от –2 147 483 648 до 2 147 483 647 в 32-разрядных системах

от –9 223 372 036 854 775 808 до 9 223 372 036 854 775 807 в 64-разрядных системах

Object 4 байта Любая ссылка на Object
Single (число с плавающей запятой одинарной точности) 4 байта от –3,402823E38 до –1,401298E-45 для отрицательных значений

от 1,401298E-45 до 3,402823E38 для положительных значений

String (переменная длина) 10 байтов + длина строки от 0 до приблизительно 2 миллиардов
String (фиксированная длина) Длина строки от 1 до приблизительно 65 400
Variant (с числами) 16 байт Любое числовое значение до диапазона типа Double
Variant (с символами) 22 байта + длина строки (24 байтов в 64-разрядных системах) Тот же диапазон как для типа String переменной длины
Определяется пользователем (используя Type) Число, необходимое для элементов Диапазон каждого элемента совпадает с диапазоном его типа данных.

Тип Variant, содержащий массив, требует на 12 байт больше, чем сам массив.

Для массивов данных любого типа требуются 20 байтов памяти плюс 4 байта на каждую размерность массива, плюс количество байтов, занимаемых самими данными. Память, занимаемая данными, может быть вычислена путем умножения количества элементов данных на размер каждого элемента.

Например, данные в одномерном массиве, состоящем из 4 элементов данных Integer размером 2 байта каждый занимают 8 байтов. 8 байтов, необходимых для данных, плюс 24 байта служебных данных составляют 32 байта полной памяти, требуемой для массива. На 64-разрядных платформах массив SAFEARRAY занимает 24 бита (плюс 4 байта на оператор Dim). Элемент pvData является 8-байтным указателем, и он должен находиться в границах 8 байтов.

Тип LongPtr не является настоящим типом данных, так как он преобразуется в тип Long в 32-разрядных средах или в тип LongLong в 64-разрядных средах. Тип LongPtr должен использоваться для представления указателя и обработки значений в операторах Declare и позволяет писать переносимый код, который может выполняться как в 32-разрядных, так и в 64-разрядных средах.

Для преобразования одного типа строковых данных в другой используется функция StrConv.

Преобразование между типами данных

В статье Функции преобразования типов приведены примеры использования следующих функций для приведения выражения к определенному типу данных: CBool, CByte, CCur, CDate, CDbl, CDec, CInt, CLng, CLngLng, CLngPtr, CSng, CStr и CVar.

Ниже приведены страницы соответствующих функций: CVErr, Fix и Int.

Функция CLngLng действительна только для 64-разрядных платформ.

Проверка типов данных

Чтобы проверить типы данных, ознакомьтесь с приведенными ниже функциями.

Возвращаемые значения функции CStr

Если expression CStr возвращает
Boolean Строка, содержащая значение True или False.
Date Строка, содержащая полный или краткий формат даты, установленный в системе.
Empty Строка нулевой длины («»).
Error Строка, содержащая слово Error и номер ошибки.
Null Ошибка во время выполнения.
Другое числовое значение Строка, содержащая число

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Целочисленный тип данных (Visual Basic)

Содержит 32-разрядные (4-байтовые) целые числа со знаком в диапазоне от -2 147 483 648 до 2 147 483 647.

Комментарии

Тип данных Integer обеспечивает оптимальную производительность на 32-разрядных процессорах. Другие целочисленные типы загружаются в память и сохраняются в памяти с более низкой скоростью.

Значение по умолчанию для типа Integer — 0.

Литеральные назначения

Переменную Integer можно объявить и инициализировать, назначив ей десятичный литерал, шестнадцатеричный литерал, восьмеричный литерал или (начиная с Visual Basic 2017) двоичный литерал. Если целочисленный литерал выходит за пределы диапазона Integer (то есть, если он меньше Int32.MinValue или больше Int32.MaxValue), возникает ошибка компиляции.

В следующем примере целые числа, равные 90 946 и представленные в виде десятичного, шестнадцатеричного и двоичного литерала, назначаются значениям Integer .

Префикс &h или &H используется для обозначения шестнадцатеричного литерала, префикса &b или &B для обозначения двоичного литерала, а префикс &o или &O для обозначения восьмеричного литерала. У десятичных литералов префиксов нет.

Начиная с Visual Basic 2017, вы также можете использовать символ подчеркивания в _ качестве разделителя цифр для повышения удобочитаемости, как показано в следующем примере.

Начиная с Visual Basic 15.5, вы также можете использовать символ подчеркивания ( _ ) в качестве начального разделителя между префиксом и шестнадцатеричными, двоичными или восьмериальными цифрами. Например:

Чтобы использовать символ подчеркивания в качестве начального разделителя, необходимо добавить следующий элемент в файл проекта Visual Basic (*.vbproj):

Числовые литералы также могут содержать I символ типа , обозначающий Integer тип данных, как показано в следующем примере.

Советы по программированию

Вопросы взаимодействия. Если вы выполняете взаимодействие с компонентами, не написанными для платформа .NET Framework, такими как объекты автоматизации или COM, помните, что Integer в других средах ширина данных отличается (16 бит). При передаче 16-разрядного аргумента такому компоненту в новом коде Visual Basic следует объявить его как Short , а не как Integer .

Расширение. Тип данных Integer можно расширить до Long , Decimal , Single или Double . Это означает, что тип Integer можно преобразовать в любой из этих типов без возникновения ошибки System.OverflowException.

Символы типов. При добавлении к литералу символа типа литерала I производится принудительное приведение литерала к типу данных Integer . При добавлении символа идентификатора типа % к любому идентификатору производится принудительное приведение этого идентификатора к типу Integer .

Тип Framework. В .NET Framework данный тип соответствует структуре System.Int32.

Диапазон

При попытке присвоить целочисленной переменной значение, лежащее за пределами диапазона данного типа, возникает ошибка. При попытке задать дробное значение оно округляется вверх или вниз до ближайшего целого значения. Если число находится точно посередине между двумя целыми числами, значение округляется до ближайшего четного целого. Такое поведение минимизирует ошибки округления, происходящие от постоянного округления среднего значения в одном направлении. В следующем коде приведены примеры округления.

Источник

Объявление переменных

При объявлении переменных обычно используется оператор Dim. Оператор объявления может быть помещен внутрь процедуры для создания переменной на уровне процедуры. Или он может быть помещен в начале модуля в разделе объявлений, чтобы создать переменную на уровне модуля.

В примере ниже создается переменная и указывается тип данных «String».

Если данный оператор отображается в процедуре, переменная strName может использоваться только в этой процедуре. Если же оператор отображается в разделе объявлений модуля, переменная strName доступна для всех процедур данного модуля, но недоступна для процедур других модулей проекта.

Чтобы предоставить доступ к переменной всем процедурам проекта, перед ней нужно поставить оператор Public, как показано в примере ниже:

Дополнительные сведения об именовании переменных см. в статье Правила именования в Visual Basic.

Переменные могут быть объявлены одним из следующих типов данных: Boolean, Byte, Integer, Long, Currency, Single, Double, Date, String (для строк переменной длины), String * length (для строк фиксированной длины), Object или Variant. Если тип данных не указан, по умолчанию присваивается тип данных Variant. Вы также можете создать определяемый пользователем тип с помощью оператора Type.

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

В приведенном ниже операторе переменные intX , intY и intZ объявлены типом Integer.

В приведенном ниже операторе intX и intY объявлены как Variant и только intZ объявлен как тип Integer.

Нет необходимости указывать тип данных переменной в операторе объявления. Если вы не укажите тип данных, переменной будет присвоен тип Variant.

Сокращение для объявления переменных x и y типом Integer в приведенном выше операторе

Сокращение для типов: % -integer; & -long; @ -currency; # -double; ! – Single; $ – String

Оператор Public

Используйте оператор Public для объявления общих переменных на уровне модуля.

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

Оператор Private

Используйте оператор Private для объявления частных переменных на уровне модуля.

Частные переменные могут использоваться только процедурами одного модуля.

На уровне модуля оператор Dim является эквивалентным оператору Private. Вы можете использовать оператор Private, чтобы упростить чтение и интерпретацию кода.

Оператор Static

Если для объявления переменной в процедуре используется оператор Static вместо оператора Dim, объявленная переменная сохраняет свое значение между вызовами в этой процедуре.

Оператор Option Explicit

В Visual Basic можно неявно объявить переменную, просто используя оператор присвоения значения. Все неявно объявленные переменные относятся к типу Variant. Для переменных типа Variant требуется больший объем памяти, чем для большинства других переменных. Приложение будет работать эффективнее, если переменные будут явно объявленными и им будет присвоен определенный тип данных. Явное объявление переменных снижает вероятность возникновения ошибок, вызванных конфликтом имен или опечатками.

Если вы не хотите, чтобы в Visual Basic были неявные объявления, то оператор Option Explicit должен стоять в модуле перед всеми процедурами. Этот оператор требует явного объявления всех переменных модуля. Если модуль содержит оператор Option Explicit, то при обнаружении необъявленной ранее переменной или опечатки в ее имени Visual Basic выдаст ошибку времени компиляции.

В программной среде Visual Basic имеется возможность задавать параметр, который будет автоматически включать оператор Option Explicit во все новые модули. Справочная информация по изменению параметров среды Visual Basic предоставлена в документации приложения. Обратите внимание, что данный параметр не меняет уже написанный код.

Статические и динамические массивы нужно объявлять в явном виде.

Объявление объектной переменной для автоматизации

При использовании приложения для управления объектами другого приложения необходимо указать ссылку на библиотеку типов этого другого приложения. Когда ссылка указана, можно объявлять объектные переменные в соответствии с наиболее подходящими для них типами. Например, если вы указываете ссылку на библиотеку типов Microsoft Excel при работе в Microsoft Word, то можете объявить переменную типа Worksheet внутри Word, чтобы она представляла объект Worksheet приложения Excel.

При использовании другого приложения для управления объектами Microsoft Access, как правило, можно объявлять объектные переменные согласно наиболее подходящим для них типам. Вы можете также использовать ключевое слово New для автоматического создания нового экземпляра объекта. Однако может возникнуть необходимость указать, что объект принадлежит Microsoft Access. Например, при объявлении объектной переменной, представляющей форму Access внутри Visual Basic, необходимо сделать различимыми объект Form приложения Access и объект Form приложения Visual Basic. Для этого следует включать имя библиотеки типов в объявление переменной, как показано в примере ниже:

Некоторые приложения не распознают отдельные объектные типы Access. Даже если в этих приложениях указана ссылка на библиотеку типов Access, все объектные переменные Access необходимо объявлять с типом Object. Также невозможно использовать ключевое слово New для создания нового экземпляра объекта.

В примере ниже показано, как объявлять переменную, представляющую экземпляр объекта Application Access в приложении, которое не распознает объектные типы Access. Затем приложение создает экземпляр объекта Application.

В документации приложения предоставлена информация о поддерживаемом им синтаксисе.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA Integer

Excel VBA Integer Data Type

In mathematics, Integers are the numbers which are complete as a whole. They do not contain any decimal values. Numbers such as 1, 10, 11, 234, etc. are the whole number called as Integers. The same concept of Integers is used in any programming language. In most of the programming language, Integers contains numbers or set of numbers which are complete whole numbers. Integers can be positive or negatives. But number with decimal digits are not integers. They are considered are Double in VBA coding.

How to Use VBA Integer Data Type in Excel?

Below are the examples to use VBA Integer Data Type in Excel.

You can download this VBA Integer Excel Template here – VBA Integer Excel Template

VBA Integer – Example #1

Let’s see a very simple example of VBA Integer.

Follow the below steps to use VBA Integer data type in Excel.

Step 1: Go to the VBA window and open a new module by selecting Module from the Insert menu tab as shown below.

VBA Integer Example 1-1

Step 2: After that, we will get a white blank page of Module. In that, write Subcategory for VBA integer or in any other name.

Code:

Sub VBAInteger1()

End Sub

VBA Integer Example 1-2

Step 3: Now use dimension DIM and assign it a name. It can be any letter or word. Here we are using “A” for it.

Code:

Sub VBAInteger1()

  Dim A

End Sub

VBA Integer Example 1-3

Step 4: After that assign the Integer function to it as shown below.

Code:

Sub VBAInteger1()

  Dim A As Integer

End Sub

VBA Integer Example 1-4

Step 5: Now DIM A can only store numbers in it. After that we can assign any numerical value to A. Here we are giving 10 to A.

Code:

Sub VBAInteger1()

  Dim A As Integer

  A = 10

End Sub

VBA Integer Example 1-5

Step 6: This completes the assigning of a number to defined dimension A. Now we need to see this value somewhere so we will use the message box to print the value assign to Integer A as shown below.

Code:

Sub VBAInteger1()

  Dim A As Integer

  A = 10

  MsgBox A

End Sub

VBA Integer Example 1-6

Step 7: Once done, compile and run the complete code by clicking on the play button which is located just below to the menu bar as shown below.

Result of Example 1-7

And then we will get a message box which has number 10, which was our assign integer value to dimension A.

VBA Integer – Example #2

In another example of VBA Integer, we will see if the concept and logic of Integers are still true about negative numbers. To demonstrate this, follow the below steps to use VBA Integer data type in Excel.

Step 1: Open a module in VBA and give it Subcategory in the name of VBA Integer or any other name as per own choice. We are giving a sequence to it.

Code:

Sub VBAInteger2()

End Sub

VBA Integer Example 2-1

Step 2: Now in a similar way, define a dimension DIM with any name, let’s says “A”.

Code:

Sub VBAInteger2()

  Dim A

End Sub

VBA Integer Example 2-2

Step 3: And now assign the dimension A as Integer as shown below.

Code:

Sub VBAInteger2()

  Dim A As Integer

End Sub

VBA Integer Example 2-3

Step 4: Now assign a negative value of 10 or any other number to A.

Code:

Sub VBAInteger2()

  Dim A As Integer

  A = -10

End Sub

VBA Integer Example 2-4

Step 5: To get this value, we will use a message box to print it as a pop-up.

Code:

Sub VBAInteger2()

  Dim A As Integer

  A = -10

  MsgBox A

End Sub

VBA Integer Example 2-5

Step 6: Now compile the code if there is any error or not. Then run. We will see as per definition, Integer can store value in negative as well.

Result of Example 2-6

VBA Integer – Example #3

We have also discussed that in VBA Integer decimal digits are not considered. Let’s see if this is applicable in reality too or not.

Follow the below steps to use VBA Integer data type in Excel.

Step 1: For this open a new module in VBA and start writing subcategory of VBA Integer in it. Here give it a proper sequence as well as shown below.

Code:

Sub VBAInteger3()

End Sub

VBA Integer Example 3-1

Step 2: Again define and choose a DIM dimension as any alphabet as per your choice. We consider the same alphabet A as taken in the above examples as well.

Code:

Sub VBAInteger3()

  Dim A

End Sub

VBA Integer Example 3-2

Step 3: Now assign the Integer function to Dim A.

Code:

Sub VBAInteger3()

  Dim A As Integer

End Sub

VBA Integer Example 3-3

Step 4: Now assign the selected dimension “A” a decimal values. We have assigned it 10.123 as shown below.

Code:

Sub VBAInteger3()

  Dim A As Integer

  A = 10.123

End Sub

VBA Integer Example 3-4

Step 5: Now select a message box for A to see the value stored in dimension A.

Code:

Sub VBAInteger3()

  Dim A As Integer

  A = 10.123

  MsgBox A

End Sub

VBA Integer Example 3-5

Step 6: Now compile and run the written code. We will see Integer function as returned the values as the whole number and decimal digits are being ignored if Integer is used.

Result of Example 3-6

If instead of Integer, we use Double function then we would get the complete decimal values.

VBA Integer – Example #4

We have seen whole numbers, negative number and decimal number with Integers. Integer function in VBA has the limit of storing the data numbers. We can store any number in Integer but there are some constraints of choosing the length of numbers. To demonstrate, Follow the below steps to use VBA Integer data type in Excel.

Step 1: Insert a new module in VBA and give it a Subcategory with the name of VBA Integer or any other name.

Code:

Sub VBAInteger4()

End Sub

VBA Integer Example 4-1

Step 2: Now use DIM for defining any dimension. Let’s consider the same alphabet used in the above examples as assign Integer function to it as shown below.

Code:

Sub VBAInteger4()

  Dim A As Integer

End Sub

VBA Integer Example 4-2

Step 3: Now let’s assign a numeric value to Integer A have 6-8 digit. Here we are assigning 1012312 number as shown below.

Code:

Sub VBAInteger4()

  Dim A As Integer

  A = 1012312

End Sub

VBA Integer Example 4-3

Step 4: And give Integer A a message box so that we will see the outcome to value stored.

Code:

Sub VBAInteger4()

  Dim A As Integer

  A = 1012312

  MsgBox A

End Sub

VBA Integer Example 4-4

Step 5: Now compile and run the above code.

Result of Example 4-5

Here we got an error message which says “Run-time error 6 – Overflow” which means that numeric value of 7 digits which we entered has crossed the limit of storage.

VBA Integer is 16bit size file which can only store values from –32768 to +32768. Beyond this, it will show the error as shown above.

VBA Integer – Example #5

We have seen all type of numbers in Integers. Now let’s consider what happens when we store any text or alphabet in Integer.

Follow the below steps to use VBA Integer data type in Excel.

Step 1: For this open a module and enter subcategory, if possible in sequence as shown below.

Code:

Sub VBAInteger5()

End Sub

Example 5-1

Step 2: Now define a dimension DIM as A and assign it with Integer.

Code:

Sub VBAInteger5()

  Dim A As Integer

End Sub

Example 5-2

Step 3: And now in defined Integer A, assign a text. Here we have assigned it “VBA Integer” along with message box.

Code:

Sub VBAInteger5()

  Dim A As Integer

  A = "VBA Integer"

  MsgBox A

End Sub

Example 5-3

Step 4: Now run the code. We will get “Run-time error 13 – Type Mismatch” error which means used function and its value don’t match.

Result of Example 5-4

Pros of Excel VBA Integer

  • We can use any type of number with an Integer data type.
  • Keeping the limit of numbers will give a positive outcome using Integer data type.

Things to Remember

  • Integers cannot be used for texts and decimal numbers.
  • For numbers beyond the limit of –32768 to +32768 use a LONG function instead of Integers.
  • Use Double function for decimal values.
  • No need to compile data step-by-step if your code is small.
  • Save the file in the Macro Enable format to avoid losing written code.

Recommended Articles

This has been a guide to Excel VBA Integer. Here we have discussed how to use VBA Integer data types in Excel along with some practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA IsNumeric
  2. VBA RGB
  3. VBA String
  4. VBA XML

Excel VBA Tutorial about data typesHave you ever thought about the main purpose of Visual Basic for Applications?

In Excel VBA Programming for Dummies, Excel authority John Walkenbach provides the following interesting answer to this question:

VBA’s main purpose is to manipulate data.

For purposes of this VBA tutorial, the key term within the above statement is “data”. If the main purpose of Visual Basic for Applications is to manipulate data, having a good understanding of what are the different VBA data types is essential for mastering VBA.

My purpose with this post is to help you understand VBA data types and how to work with them. In this guide, I cover and thoroughly explain the most relevant aspects of the different VBA data types, including the following:

In this particular post, I don’t cover the topic of variable declaration in detail. This is covered in this blog post about variable declaration.

How Data Is Stored And Why VBA Data Types Are Important

Data is generally stored in the computer’s memory. If you have a basic understanding of computers, you’re probably familiar with how this works.

However, for VBA purposes, there is an important distinction to be made between objects and variables. As Walkenbach explains in Excel VBA Programming for Dummies:

  • Some data is stored in objects.
  • Other data is stored in variables.

I explain what “objects” and “variables” are in this VBA Tutorial for Beginners. To summarize:

  • An object is what is manipulated by Visual Basic for Applications.

    Some examples of objects are Excel workbooks, worksheets, cell ranges and cells.

  • A variable is a storage location paired with a name. You generally use variables to represent a particular value. In other words, variables act as placeholders for values.

    You can create variables in Visual Basic for Applications by declaring them. You determine the name and characteristics of any variable you create. One of the characteristics that you can determine is the VBA data type.

The ability to determine the characteristics of the variables you create in VBA is probably the main reason why understanding VBA data types is important. Let’s see why this is the case:

VBA data types determine the way in which data is stored in the memory.

There are several VBA data types. These data types have different nominal allocation requirements. This means that different types use a different amount of bytes.

The general rule that you should apply when determining which data type to use is set forth by John Walkenbach in Excel VBA Programming for Dummies:

In general, choose the data type that uses the smallest number of bytes but can still handle all the data you want to store (…).

The reason for this is that there is an inverse relation between execution speed and the amount of bytes used by the relevant data. In other words, the more bytes your data uses, the slower your VBA application runs.

As this makes it clear, in order to be able to make appropriate decisions about the VBA data types that you want to use, you must understand the basic characteristics of each of the main types. Mastering this topic is very important, particularly as you start creating and developing more complex VBA applications. The main reason for this is that inadequate choices of VBA data types can result in slower execution of those applications and, in general, an inefficient use of the memory.

Introduction To Why You Shouldn’t Always Allow VBA To Handle Data Types Automatically

Programming languages are usually classified as strongly typed or weakly typed.

Strongly typed languages usually require that you define the data type for every variable that you use. Visual Basic for Applications isn’t one of these languages. Therefore, VBA is able to handle the details related to data types automatically.

More precisely, if you don’t declare the VBA data type for a particular variable, Visual Basic for Applications uses the default type. The default VBA data type is called Variant, and I explain it below.

The question is:

Should you allow Visual Basic for Applications to automatically set the VBA data types for the variables you use?

Generally, no. You should get used to declaring the VBA data types of the variables you create always.

However, the answer to the question isn’t as straightforward as the statement above may make it seem.

Allowing Visual Basic for Application to automatically deal with VBA data types for variables has advantages. The main advantage is, evidently, that by allowing VBA to handle data types, you don’t have to do it yourself. This may sound more convenient, but wait…

As I mentioned above, inappropriate choices of VBA data types can result in problems down the road, including slower application execution. More precisely, if you always rely on the default Variant data type, you’ll likely start noticing that your VBA applications run relatively slow and require more memory than necessary. I explain the reason for this below.

Therefore, if you’re committed to becoming a powerful VBA user, you must have a good grasp of VBA data types and, when required, be able to choose the most appropriate one.

So, should you always deal with VBA data types yourself?

Generally, declaring the variables that you use in order to determine their VBA data type explicitly is a good practice. However, if you don’t want to do this, you can carry out your own cost-benefit analysis considering the following criteria:

  • As explained in Excel VBA Programming for Dummies, “letting VBA handle your data typing results in slower execution and inefficient memory use.”
  • Despite the above, Microsoft explains how using the Variant data type allows you to handle data more flexibly.
  • How noticeable are the issues of slower execution and inefficient memory use generally depends on the size and complexity of the relevant VBA application. Therefore, in small applications or applications that don’t use many variables, allowing Visual Basic for Applications to handle the VBA data types directly shouldn’t generate big issues.
  • However, when you’re working with big and/or complex applications, letting VBA deal with data types automatically isn’t very advisable. In these cases, you want to conserve as much memory as possible. A good knowledge of VBA data types is essential in achieving an efficient use of memory when developing VBA applications.

In the words of John Walkenbach:

Letting VBA handle data types may seem like an easy way out – but remember that you sacrifice speed and memory.

In addition to the above, as explained in Mastering VBA for Microsoft Office 2013, not declaring the variables makes your VBA code harder to read and debug.

There are additional reasons to always declare your variables when working with Visual Basic for Applications. Let’s take a look at 2 further reasons, explained by Walkenbach in Excel 2013 Power Programming with VBA and Excel VBA Programming for Dummies.

Reason #1: Possible Misinterpretation Of Intended VBA Data Type When Using Variant VBA Data Type

According to Mastering VBA for Microsoft Office 2013, one of the disadvantages of using the Variant VBA data type is that VBA can misinterpret the data sub-type that you intended. This can lead to “rather obscure bugs”.

Let’s take a look at a very simple example, involving strings and numbers, to illustrate this point.

Take a look at the following piece of very simple VBA code.

VBA code with Variant data type

This Excel VBA Data Types Tutorial is accompanied by an Excel workbook containing the data and macros I use (including the Variant_Concatenation macro above). You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

The 3 main statements of the Variant_Concatenation macro above carry out the following actions:

  • “ExVar = “1”” assigns 1 to the variable ExVar. Since ExVar hasn’t been declared, it is of the Variant VBA data type.
  • “ExVar = ExVar + ExVar + ExVar” performs an operation. The + operator is applied to the variable ExVar.
  • “MsgBox ExVar” displays a dialog box with the expression that is currently stored by the variable ExVar.

The question is, what is the value displayed in the message that appears within the dialog box at the end of the Variant_Concatenation macro?

At first glance, it may appear that the dialog box should display the number 3. After all, the second line seems to be adding ExVar three times, and ExVar has previously been assigned 1. 1 + 1 + 1 = 3, right?

Well…

Even though the reasoning above makes sense, the rules that apply in Visual Basic for Applications can be slightly different to what we’re used to. Let’s take a look at the actual dialog box that is displayed when I run the Variant_Concatenation macro:

Example of result obtained when working with VBA data type Variant

111? Where’s the 3 that we were expecting?

If you’re familiar with VBA, you may have noticed some of the issues that the piece of VBA code that appears above has. Note how, when assigning 1 to the variable ExVar, the number 1 is enclosed in quotation marks (“”).

Example of VBA data type Variant variable

This means that the number 1 is actually a string instead of a number. When you’re working with variables that contain strings and you use the + operator, Visual Basic for Applications concatenates all the strings.

Therefore, if “1” is a string, “1 + 1 + 1” is not equal to 3. The correct answer, in that case, is the one that appears in the dialog box above: 111.

Microsoft explains this particular characteristic of the Variant VBA data type by stating that, when a Variant variable contains digits, the interpretation depends on the context. Therefore, depending on such context, those digits may be interpreted as either a string (as in the example above) or the actual value.

This particular problem is not caused exclusively by the use of the Variant VBA data type. The assignment of the variable could’ve probably been better structured. Nonetheless, this is a further reason to avoid relying on the Variant data type always.

If you still want to rely on the Variant VBA data type, there are ways to determine the VBA data sub-type of any Variant variable. I show how you can apply these methods to the Variant_Concatenation macro in a section below.

Reason #2: Shortcut For Inserting Variables In VBA Code When Working With Declared Variables

Let’s take a look at the following piece of VBA code. The purpose of this macro is to delete blank rows in Excel. Notice how the variable iCounter is properly declared.

vba code example why declare variables

Imagine that you’re creating the first version of this macro. And you’re typing at the following point:

Shortcut for typing VBA code with declared variables

Theoretically, you must type the whole name of the variable: “iCounter”. However, since the variable has been declared at the beginning of the Sub procedure, you can use the keyboard shortcut “Ctrl + Spacebar” once you’ve written the first couple of characters (usually 2 or 3 are enough). When you do this, the Visual Basic Editor does one of the following:

  • If it knows exactly to what particular word (this applies to variables, reserved words or functions) you’re referring to, it completes the entry.

    This is what happens in the case above. The following image shows what happens once I use the “Ctrl + Spacebar” shortcut:

    Example of VBA variable typing shortcut

  • If it isn’t sure about what word you’re referring to, it displays a list of possible words from which you can select.

    For example, let’s assume for a second that the Delete_Empty_Rows macro that appears above has 2 declared variables: iCounter and iCounter1. In that case, the Visual Basic Editor looks as follows:

    Example of shortcut for completing VBA variables

How To Remind Yourself To Declare VBA Data Types

You may be convinced that it is a good idea to always declare VBA data types when creating variables. However…

We all forget things sometimes.

Therefore, it’s not surprising that, from time to time and despite our best efforts to the contrary, we forget to determine the VBA data type of a variable. Additionally, since Visual Basic for Applications is able to handle VBA data types automatically, you may not even notice this happening.

Fortunately, you can force yourself to declare all the variables that you use. To do this, you simply need to use the Option Explicit statement.

When enabled, the Option Explicit statement requires that you explicitly define all the variables in the VBA module where that particular statement appears.

How do you enable the Option Explicit statement?

Easy, simply type “Option Explicit” at the top (before any other code) of the relevant VBA module. You only need to do this once per module. However, you’ll need to include the statement in any separate modules to which you want the Option Explicit option to apply.

If you want to take it a step further, you can have the Visual Basic Editor automatically insert the Option Explicit statement at the beginning of any future VBA modules. You can do this by customizing the code settings of the VBE in order to enable the Require Variable Declaration option. I explain how to do this in this VBE tutorial.

If the Option Explicit statement is enabled, you’ll simply not be able to run VBA code that contains undeclared variables.

Enabling the Option Explicit statement has an additional advantage: it helps you to spot typos or misspellings that, otherwise, might have been difficult to see. Let’s see how this works in practice by checking a macro that deletes empty rows.

For this example, I’ll use the macro whose VBA code appears in the image below, named Delete_Empty_Rows_2. I explain this macro in detail (and show how it works in practice) in this post.

VBA code including VBA data types

In this particular macro, 2 variables are declared at the beginning: aRow and BlankRows. Both variables are of the Range VBA data type.

Now, let’s focus on the BlankRows variable. The image below shows how this particular variable is used several times in this particular Sub procedure.

VBA data type example: variable

Imagine that, while typing the VBA code, a typo somehow manages to squeeze in (just one). Instead of typing “BlankRows” (the appropriate name), you type “BlamkRows” (similar, but not the same).

Example of typo in VBA variable name

As you may imagine, such typos may be difficult to spot in some situations. If you don’t notice the mistake, the macro may not work as originally intended.

However, if you have enabled the Option Explicit statement, Visual Basic for Applications displays a prominent warning. Take a look at the screenshot below and notice how easy is to notice that “BlankRows” is misspelled.

vba code with variable not defined

Variant VBA Data Type

Variant is the default VBA data type. In other words, this is the data type that Visual Basic for Applications uses when you don’t determine the type yourself at the moment of declaring a variable. You can, however, also declare a Variant variable explicitly.

In Excel VBA Programming for Dummies, John Walkenbach likens the Variant VBA data type with a chameleon. In other words, data that is of the Variant type “changes type depending on what you do with it.” This allows you to work with data more flexibly.

This sounds great! Who wouldn’t want this?

Well…

Not having to worry about VBA data types sounds great in theory but isn’t as simple in practice. Variant is, as a general rule, not the most efficient data type. This inefficiency is caused, funnily enough, by its chameleon-like characteristics.

More precisely, in order for Variant to behave like a chameleon and change of type depending on the context, Visual Basic for Applications must carry out certain checks for determining like which type should Variant behave. As you can imagine, carrying out these checks repeatedly requires more time and memory.

As explained in Mastering VBA for Microsoft Office 2013, the Variant VBA data type requires more memory than any of the other data types, excluding very long strings. More precisely:

  • Variant variables with numbers require 16 bytes of memory.
  • Variables of the Variant data type with characters usually require 22 bytes of memory plus the memory required by the string.

And this is one of the reasons why I generally suggest that you get used to declaring the VBA data type of your variables and use other VBA data types different from Variant. When you do this, Visual Basic for Applications doesn’t need to be constantly carrying checks (as it does with Variant). This usually results in faster, snappier and better VBA applications, and more efficient memory management.

Let’s take a look at a few additional characteristics of the Variant VBA data type:

  • When it comes to numeric data, you can store numbers within the following ranges:

    For negative numbers: -1.797693134862315E308 to -4.94066E-324.

    For positive numbers: 4.94066E-324 to 1.797693134862315E308.

  • Variant’s ability to handle different types of VBA data isn’t absolute. In particular, Variant variables can’t contain fixed-length string data.

    I explain what fixed-length string data is below. In that same section, I also explain the String data type, which is the one you’ll have to use in such cases.

  • Variables of the Variant VBA data type can contain 4 additional special values:

    Value #1: Empty, meaning that no value has been assigned to the variable. You can see an example of this below.

    Value #2: Error, which is used for purposes of indicating errors in the relevant procedure.

    Value #3: Nothing, which you can use when disassociating a variable from an object it was previously associated to.

    Value #4: Null, which indicates that the variable contains no valid data.

Byte VBA Data Type

The Byte VBA data type is the one that requires less memory: only 1 byte.

Variables whose VBA data type is Byte can be used to store numbers between 0 and 255.

Boolean VBA Data Type

If you’ve ever studied Boolean algebra, you may remember that the states of the variables are TRUE and FALSE.

The Boolean VBA Data Type follows this logic. In other words, variables whose VBA data type is Boolean can only be set to one of the following 2 values:

  • TRUE.
  • FALSE.

In general Boolean algebra, TRUE and FALSE are usually denoted by 1 and 0 respectively. However, in Visual Basic for Applications, conversions between Booleans and numeric VBA data types work slightly different:

  • When converting a Boolean variable to a numeric VBA data type, TRUE becomes –1 and FALSE becomes 0.
  • When converting a numeric VBA data type into a Boolean, 0 becomes FALSE and all other values (regardless of whether they’re negative or positive) become TRUE.

Boolean variables require 2 bytes of memory.

Currency VBA Data Type

As you’d expect, the Currency VBA data type is generally used in connection with monetary matters. However, as I explain below, you can use it for other purposes as well.

The Currency VBA data type is exact. The Single and Double data types that I explain below are rounded.

Currency variables can be used to store both positive and negative numbers. They’re stored as numbers in an integer format that is scaled by 10,000. As a consequence, these variables give fixed-point numbers whose length is up to:

  • 15 digits to the left side of the decimal point.
  • 4 digits to the right side of the decimal point.

As a consequence of the above, this data type allows for a range of values between -922,337,203,685,477.5808 and 922,337,203,685,477.5807.

Due to the fact that the Currency VBA data type is exact and these variables give fixed-point numbers, Currency is particularly useful for monetary calculations or fixed-point calculations where accuracy is very important.

The Currency data type takes up 8 bytes of memory.

Date VBA Data Type

This is another VBA data type whose name is self-explanatory.

Indeed, you won’t be surprised to confirm that Date variables can be used to store values that represent dates, times or both.

However, if you’ve been working with Excel for a while, you may have noticed that the way Excel and Visual Basic for Applications work with numbers isn’t necessarily the easiest to understand. Therefore, I provide a short introduction to this topic below.

As explained in Mastering VBA for Microsoft Office 2013, “VBA works with dates and times as floating-point numbers”. Let’s take a quick look at what this means:

Introduction To Floating-Point And Fixed-Point Numbers

Floating-point is a way of representing numbers. Under this formula, a number is represented in an approximate way to a certain number of significant digits. This is then scaled using an exponent.

However, the most critical point to understand is that the reason why this formula is called “floating-point” is due to the fact that the decimal point “floats”.

Computers can also store numbers as fixed-point numbers. You can see an example of this in the Currency VBA data type explained above. In the case of fixed-point numbers, the decimal points doesn’t “float”. It remains fixed in a certain location and, therefore, the number has always a fixed number of digits after or before the decimal point.

Working with floating-point numbers, generally, demands more computational resources. Therefore, the suggestion made in Mastering VBA for Microsoft Office 2013 is to use fixed-point numbers “whenever practical”.

Date Variables

Now that you have a basic understanding of floating-point and fixed-point numbers, let’s take a closer look at what the Date VBA data type can do.

In general terms, Date variables can store values representing:

  • Dates between January 1, 100 and December 31, 9999.
  • Times between midnight (00:00:00) and 23:59:59.

These values are stored as floating-point numbers, as follows:

  • The date appears to the left of the decimal point.
  • The time appears to the right of the decimal point.

The following are examples of how variables of numeric VBA data types are converted to the Date type:

  • 0 represents midnight.
  • 0.5 is midday.
  • Negative integers are dates before December 30, 1899.

Date VBA variables require 8 bytes of memory.

Decimal VBA Data Type

Decimal is one of VBA’s numeric data types.

More precisely, the Decimal VBA data type can be used to store integers scaled by a power of 10. This scaling factor varies depending on how many digits there are to the right side of the decimal point. The maximum number of these digits that a Decimal variable can hold is 28.

Considering the above, the following are the largest and smallest values for a Decimal variable:

  • If there are no decimal places at all: +/-79,228,162,514,264,337,593,543,950,335.
  • With the maximum number of decimal places (28), the largest value is +/-7.9228162514264337593543950335 and the smallest (excluding 0) is +/-0.0000000000000000000000000001.

In other words, the Decimal VBA data type gives you the largest amount of digits in order to represent a particular number. Therefore, it’s more appropriate for cases where you are performing calculations with large numbers that need to be very precise and can’t be subject to rounding errors.

The precision of the Decimal data type, comes at a cost in the form of a large memory requirement. The Decimal VBA data type requires 12 bytes, which is larger than the other numeric data types.

As explained by Microsoft, you can’t declare the Decimal VBA data type directly (just as you do with the other data types). Strictly speaking, Decimal is a sub-type of Variant. Therefore, in order to use Decimal, you must use the CDec conversion function.

Double VBA Data Type

The Double VBA data type is one of the non-integer numeric data types. This means that, just as decimal, it can be used to hold both integers and fractions.

More precisely, you can use Double to store floating-point numbers within the following ranges:

  • For negative numbers: -1.79769313486231E308 to -4.94065645841247E-324.
  • For positive numbers: 4.94065645841247E-324 to 1.79769313486232E308.

I provide a brief introduction to floating-point numbers above. You may however be wondering, why is this type of VBA data called double?

“Double” stands for “double-precision floating-point”. This makes reference to the number format which determines how the computer handles the number. There is also a Single VBA data type (explained below).

Double VBA variables require 8 bytes of memory.

Integer VBA Data Type

You can use the Integer VBA data type for storing integers between -32,768 to 32,767.

Integer variables only require 2 bytes. Due to its low memory requirements, the Integer VBA data type is usually the most efficient and better performing option for purposes of storing integers that fall within its range.

As explained by Microsoft, you can also use the Integer data type for purposes of representing enumerated values. Enumerated values:

  • Usually contain a finite set of unique natural numbers. Each of these numbers has a particular meaning.
  • Are commonly used for purposes of selecting among different options.

Long VBA Data Type

“Long” makes reference to “Long Integer”. As implied by its name, you can use the Long VBA data type for storing integer values that are within a “longer” range than the range of the Integer data type.

More precisely, by using the Long VBA data type you can store numbers between -2,147,483,648 and 2,147,483,647. If this range is still not enough for your purposes, you may want to use the Double VBA data type.

Long variables require 4 bytes of memory. As you’d expect, this is more than Integer variables (2), but less than Double variables (8).

Object VBA Data Type

You can use the Object VBA data type for purposes of storing addresses that refer to objects. In general, Object variables are a convenient way to refer to objects.

Variables of the Object type take up 4 bytes of memory.

Single VBA Data Type

I anticipated the existence of the Single VBA data type when introducing the Double type above. “Single” refers to “single-precision floating-point”, the number format that determines how the computer handles the number.

You can use the Single VBA data type for storing numbers within the following ranges:

  • For negative values: -3.402823E38 to -1.401298E-45.
  • For positive values: 1.401298E-45 to 3.402823E38.

Single variables require 4 bytes, half of those required by the Double VBA data type (8).

String VBA Data Type

For purposes of programming, a string is generally defined as a sequence of characters that represents the characters themselves (not a numeric value or other similar thing). Within Visual Basic for Applications, the String VBA data type is generally used to store text. However, this doesn’t mean that you should only use letters within String variables. In addition to letters, String variables can contain numbers, spaces, punctuation and special characters.

There are 2 different kinds of Strings. The amount of characters and memory required varies depending on the type.

Type #1: Variable-Length Strings

Variable-length String variables can contain anything from 0 up to approximately 2 billion characters. They take up 10 bytes of memory plus the memory that is required for the string itself.

Type #2: Fixed-Length Strings

Fixed-length String variables can contain between 1 and approximately 64,000 characters. These particular String variables require the amount of memory required by the string.

According to Mastering VBA for Microsoft Office 2013, fixed-length String variables “are rarely used in most programming”. The main exception is when managing databases where a rule specifying a maximum string length applies.

You may wonder what happens if the data that is assigned to a fixed-length String variable is different from the fixed length. Visual Basic for Applications handles this matter differently depending on whether the data assigned is shorter or longer than the fixed length:

  • If the data assigned is shorter, VBA adds trailing spaces in order to reach the fixed length.
  • If the assigned data is longer, Visual Basic for Applications truncates the data after the fixed length is reached. For these purposes, characters are counted from left to right.

    For example, if you assign the string “Tutorial” to a fixed-length String variable with a length of 3 characters, Visual Basic for Applications only stores “Tut”.

Other VBA Data Types

The above sections explain the most common VBA data types. From time to time, you may encounter some other data types, such as the ones I briefly introduce below.

LongLong VBA Data Type

The LongLong VBA data type is only valid on 64-bit platforms. This makes reference to how your computer is handling information.

According to tech website TweakTown, 92.8% of new Windows computers utilize 64-bit operating systems. You can find more information about the 32-bit and 64-bit versions of Windows here, including how to check which version your computer is running.

You can use the LongLong VBA data type to store numbers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807.

LongLong variables require 8 bytes of memory.

LongPtr VBA Data Type

LongPtr isn’t (strictly speaking) a VBA data type. More precisely, the way LongPtr behaves depends on which platform is the relevant procedure running.

  • In 32-bit platforms, LongPtr becomes Long.
  • In 64-bit platforms, LongPtr becomes LongLong.

Both the range of values that can be stored using a LongPtr variable and the memory requirements vary accordingly.

As explained by Microsoft, one of the main uses of LongPtr is for pointers and handlers.

User-Defined VBA Data Types

Visual Basic for Applications allows you to create your own VBA data types. As you’d expect, these data types are known as user-defined data types.

In order to create a user-defined data type, you use the Type statement. These data types can contain 1 or more elements from the following:

  • Data types.
  • Arrays.
  • User-defined data types that have been defined previously.

User-defined VBA data types are highly dependent on their different components. For example:

  • The number of bytes required by a particular user-defined VBA data type depends on its elements.
  • The range of each of those elements is the one that applies to the relevant data type.

I may explain further details of user-defined VBA data types in future VBA tutorials. Please make sure to enter your email address below if you want to join the Power Spreadsheets Newsletter and be notified whenever I publish new material.

How To Decide Which VBA Data Type To Use

Now that you know about the main different VBA data types, you may be wondering…

How do I decide which VBA data type to use for a particular variable?

You already know the basic rule for choosing data types proposed by John Walkenbach. Under this general rule, your choice of data type is determined by the answers to the following 2 questions:

  • Which VBA data type(s) is(are) able to handle the data that you want to store?
  • Out of the VBA data type(s) that can handle the data you want to store, which data type uses the smallest number of bytes?

These guidelines may still feel a little bit general. Therefore, below are some general suggestions provided by Richard Mansfield in Mastering VBA for Microsoft Office 2013:

  • If the relevant variable will only contain logical values (TRUE and FALSE), use the Boolean VBA data type.
  • If the variable will always contain a string, use the String VBA data type.
  • If the variable will contain an integer use either the Integer or the Long VBA data type. The choice between Integer and Long depends on how big the relevant numbers are.

    Remember that neither Integer nor Long variables can be used to store fractions. Which takes us to the following point…

  • If the variable you’re declaring may contain fractions, use the Single or Double VBA data types. The decision to choose one or the other depends on the range of values the variable may store.
  • If you’ll be using the variable in operations where you can’t have rounding errors (you require no-rounding fractions), use the Currency or Decimal VBA data types. As in the previous cases, the exact choice of variable depends on the size of the exact numbers you’ll be storing.

You’ll notice that, in several of the above cases, which data type you should use depends on the range of values that you want the variable to be able to handle. Learning how to choose the appropriate VBA data type (considering factors such as the range) is critical and, as computers become more powerful and VBA develops, there may be further changes to the available data types.

For example, loop counters used to be declared using the Integer VBA data type, which can’t be larger than 32,767. Recent versions of Microsoft Excel can have 1,048,576 rows. This clearly exceeds the range that Integer variables can handle. Therefore, a more appropriate choice is using the Long VBA data type.

As you practice with Visual Basic for Applications, you’ll start becoming better and more comfortable deciding which VBA data type to use.

However, if you’re still not sure how these rules apply to a particular situation, this is a case where the Variant VBA data type may be of help. Let’s take a look at…

How To Find Out The VBA Data Sub-Type Of A Variant Variable

Remember that the Variant VBA data type behaves like a chameleon. Variant changes its sub-type depending on what particular action you’re carrying out with it.

Despite the downsides of relying on the Variant VBA data type that I have explained throughout this VBA tutorial, Variant can be quite helpful for purposes of testing a particular variable and determining what is the most appropriate data type to use.

Let’s take a look at 3 ways you can do this. In all examples, I use the Variant_Concatenation macro that I used above to illustrate how the Variant data type may result in possible misinterpretations of your intended VBA data type.

This Excel VBA Data Types Tutorial is accompanied by an Excel workbook containing the data and macros I use. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Testing A Variable Using The Variant VBA Data Type

I may cover the topic of debugging in future VBA tutorials. In this section I simply show you how to use the Locals Window and the Step Into command for purposes of determining which particular data type to use.

You can do this in the following 6 simple steps, as explained in Mastering VBA for Microsoft Office 2013.

Step #1: Display The Locals Window

For purposes of this process, the Locals Window of the Visual Basic Editor must be visible. This window displays all the variables in the relevant procedure, as well as their values.

You can usually see the Locals Window at the bottom of the VBE.

Location of the Locals Window in the VBE

If you can’t see the Locals Window in your VBE, you can ask the Visual Basic Editor to display it by clicking on “Locals Window” within the View menu.

Open Locals Window in Visual Basic Editor

Step #2: Step Into The Relevant VBA Sub Procedure

You can step into a procedure by using the “F8” keyboard shortcut or by choosing “Step Into” in the Debug menu of the Visual Basic Editor.

step into vba sub procedure

Once you’ve stepped into the procedure, the Visual Basic Editor takes you to the first line of code in the macro.

Visual Basic Editor when stepping into macro

Step #3: Step Through Procedure And Find Out Variant Sub-type of Variable

Every time you click the Step into command or the “F8” keyboard shortcut, the Visual Basic Editor executes a line of code and steps into the next. Do this for purposes of stepping through the VBA Sub procedure and finding out what is the Variant VBA sub-type that Visual Basic for Applications automatically assigns to the relevant variable.

The following 2 screenshots show how this works in the case of the Variant_Concatenation macro that’s been used as example:

  • Notice how, initially, the ExVar variable contains the special value Empty. This means that the variable hasn’t been initialized.

    Variant VBA data sub-type

  • In the following screenshot you can see how the ExVar variable is of the String sub-type just one step later.

    Variable with String VBA data sub-type

Bear in mind that just because a variable of the Variant VBA data type is behaving in a certain way, it doesn’t mean that this is the most appropriate data type to use. Remember that one of the possible downsides of using this particular data type is that the Visual Basic Editor may misinterpret your intended VBA data type.

Step #4: Test The Procedure

Step a couple of times into the procedure following the steps I described above. Your purpose is to determine that the variable is being assigned the same VBA data sub-type in a consistent manner. Once you’ve determined that this is the case, you can proceed to the step #5.

Step #5: Declare Variable With VBA Data Type

Once you’ve determined that the relevant variable is behaving appropriately and that it is being assigned the same data sub-type in a consistent manner, declare the variable using the VBA data type you’ve found.

Step #6: Test VBA Code

Once you’ve determined the VBA data type that you consider appropriate for the variable, test your VBA code in order to make sure that the data type is the right one.

Finding Out The VBA Data Sub-Type Of A Variant Variable Using The TypeName Function

Visual Basic for Applications allows you to determine the VBA data type of a variable by using the TypeName function. When applied, the TypeName function returns a string displaying the VBA data sub-type information of a particular Variant variable.

Let’s see how you can apply the TypeName function to the Variant_Concatenation macro.

For these purposes, I start with the VBA code of the original macro that I use in the previous examples:

Example of VBA code for TypeName function

And I add several message boxes that display the VBA data type of the ExVar variable at different stages of execution of the macro. The new macro is called “Variant_Concatenation_TypeName”. The relevant statements (which are highlighted in the image below) are of the form “MsgBox TypeName (varname)”, where:

  • “MsgBox” makes reference to the MsgBox function.
  • “varname” is the Variant variable whose VBA data sub-type you want to find out (in this case ExVar).

VBA code with TypeName function

You already know that, since the ExVar variable isn’t declared, its VBA data type is Variant. Additionally, based on the previous section where we used the Step Into command for purposes of testing the variable, you know that the ExVar variable is not initialized at first (is Empty) and, after the assignment is made, it behaves like a string variable.

The expectations described above match what the message boxes display once the Variant_Concatenation_TypeName variable is executed. More precisely:

  • The first message box to appear returns Empty, as expected.

    Screenshot of message box with Empty VBA data type

  • The second and third message boxes confirm that (now) the ExVar variable is of the String VBA data sub-type.

    Message box with String VBA data type

Finding Out The VBA Data Sub-Type Of A Variant Variable Using The VarType Function

You can also use the VarType function for purposes of finding out the VBA data type of a particular variable.

The way VarType works is very similar to the way the TypeName function works. More precisely, the VarType function returns an integer that indicates what is the VBA sub-type of a Variant variable. The following are the values that can be returned by VarType:

  • 0: Empty.
  • 1: Null.
  • 2: Integer.
  • 3: Long.
  • 4: Single.
  • 5: Double.
  • 6: Currency.
  • 7: Date.
  • 8: String.
  • 9: Object.
  • 10: Error.
  • 11: Boolean.
  • 12: Variant. This particular value is only used with arrays.
  • 13: Data access object.
  • 14: Decimal.
  • 17: Byte.
  • 36: Variant containing user-defined types.
  • 8192: Array.

The syntax of VarType is also very similar to that of TypeName. More precisely, the syntax of VarType is “VarType (varname)”, where “varname” is the Variant variable whose VBA data sub-type you want to find.

Therefore, I simply create a new macro called “Variant_Concatenation_VarType”. The VBA code is almost the same as that in the previous example (Variant_Concatenation_TypeName). The only difference is that, instead of using TypeName, I use VarType.

VBA code with VarType function

You probably expect that, when the Variant_Concatenation_VarType macro is executed, the first message box returns the value that corresponds to Empty, while the second and third message boxes display the value corresponding to String.

This is indeed what happens:

  • The first message box to be displayed returns the number 0. This corresponds to Empty.

    Message box with value for empty VarType

  • The second and third message boxes display the number 8. This number makes reference to strings.

    Message box displaying value for String VBA data type

Conclusion

The main purpose of Visual Basic for Applications is to manipulate data. Therefore, in order to master VBA and macros, you must have a good understanding of what are the different VBA data types.

After reading this VBA tutorial you probably have a good understanding of the different VBA data types that you can use, and how to determine which type to use in each situation. Choosing which data type to use may seem awkward or a little bit difficult at first, but don’t worry…

As with most aspects of Visual Basic for Applications, the more you practice, the better you’ll become. Therefore, make sure you start using the knowledge about VBA data types that you’ve gained by reading this post in your day-to-day activities.

Books Referenced In This Excel Tutorial

  • Mansfield, Richard (2013). Mastering VBA for Microsoft Office 2013. Indianapolis, IN: John Wiley & Sons Inc.
  • Walkenbach, John (2013). Excel VBA Programming for Dummies. Hoboken, NJ: John Wiley & Sons Inc.
  • Walkenbach, John (2013). Excel 2013 Power Programming with VBA. Hoboken, NJ: John Wiley & Sons Inc.

Хитрости »

1 Май 2011              225500 просмотров


Что такое переменная и как правильно её объявить?

Переменная — это некий контейнер, в котором VBA хранит данные. Если подробнее, то это как коробочка, в которую Вы можете положить что-то на хранение, а затем по мере необходимости достать. Только в данном случае в переменной мы храним число, строку или иные данные, которые затем можем извлекать из неё и использовать в коде по мере необходимости.

Для чего нужна переменная? Чтобы хранить значение и применить его позже в любой момент. Например, в ячейке А1 записана сумма, а нажатием на кнопку запускается обновление отчета. После обновления отчета сумма в А1 изменится. Необходимо сверить сумму до обновления с суммой после и в зависимости от этого сделать какое-либо действие. Переменная как раз позволит запомнить значение ячейки до того, как она обновится и использовать именно это значение после обновления.


  • Требования к переменным
  • Типы данных, хранимых в переменных
  • Как объявлять переменные
  • Как правильно назвать переменную
  • Пример использования переменных
  • Константы

В качестве имен переменных можно использовать символы букв и числа, но первой в имени переменной всегда должна быть буква. Не допускается использование точки, запятой, пробела и иных знаков препинания, кроме нижнего подчеркивания. Длина имени не должна превышать 254 символов. Так же нельзя использовать в качестве имен для переменных зарезервированные константы редактора VBA(например Sub, Msgbox, ubound, Date и т.п.). Так же для переменных неважен регистр букв.

 
Теперь рассмотрим основные декларированные в VBA

типы данных, которые можно хранить в переменных:

Тип данных Занимает байт в памяти Пределы значений
Byte 1 Целые числа от 0 до 255
Boolean 2 True или False
Integer 2 Целые числа от (-32768) до 32767
Long 4 Целые числа от (-2147483648) до 2147483647
Single 4 От (–3.402823Е+38) до (–1.401298Е-45) и от 1.401298Е-45 до 3.402823Е+38
Double 8 От ±1.79769313486232Е+308 до ±4.94065645841247Е-324
Decimal 12 От ±79228162514264337593543950335 без десятичных знаков до ±7,9228162514264337593543950335 с 28-ю знаками после запятой
Currency 8 От (–922337203685477.5808) до 922337203685477.5807
Date 8 От 01.01.100 до 31.12.9999(не надо путать с датами в Excel — 01.01.1900 до 31.12.9999)
String 10(+длина строки) От 0 до 65400 символов для фиксированных строк и чуть более 2 млрд. для строк переменной длины
Object 4 Любой объект
Array Определяется кол-вом и размером элементов
Variant от 16-ти Любой из встроенных типов данных

Как видно из таблицы больше всего памяти занимает Variant. Притом это если он хранит числовые данные. Если же такая переменная будет хранить данные строкового типа(текст), то размер занимаемой памяти будет измеряться уже начиная с 22 байт + длина строки, хранящейся в переменной. Чем больше памяти занимает переменная, тем дольше она инициализируется в памяти и тем медленнее код будет выполняться. Вот поэтому и важно явно задавать тип данных, хранимых в переменной — это называется объявить переменную.

Тип данных Decimal больше не используется, поэтому объявить переменную данного типа в VBA не получится — подобная попытка приведет к синтаксической ошибке. Для работы с данными типа Decimal переменную необходимо изначально объявить как Variant или вообще без типа (например Dim a), т.к. тип данных Variant используется в VBA по умолчанию и принимает любой тип данных.

Так же переменным можно назначать и другие типы данных, которых нет в таблице выше — это типы, которые поддерживаются объектной моделью приложений, к которым «подключен» VBA. Например, если зайти в VBA из Excel, то библиотека типов объектной модели Excel подключена по умолчанию и для переменных становится доступно множество типов этой объектной модели. Многие из них знакомы всем: Workbook, Worksheet, Range, Cells, Chart и т.д. Т.е. это книги, листы, ячейки, диаграммы. Типов много, почти на каждый объект и коллекцию. Рассматривать здесь все бессмысленно. Могу лишь привести пару строк кода:

Dim rRange as Range 'назначили переменной тип ячейка/диапазон
Set rRange = Range("A1") 'присвоили ссылку на ячейку A1 текущего листа

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

как объявлять переменные

На самом деле все очень просто. Это делается при помощи операторов области действия: Dim, Public,Static и оператора присвоения типа As. Самый распространенный оператор — Dim. Его и возьмем в качестве примера. Синтаксис объявления:

[оператор области действия] Имя_переменной As [тип данных]

Очень частая ошибка при объявлении переменных, совершаемая начинающими изучать VBA:

Dim MyVar1, MyVar2, MyVar3 As Integer

Вроде бы исходя из логики всем переменным присвоен тип данных Integer. Но это ошибочное суждение. Тип Integer присвоен только последней переменной, к которой он «привязан» оператором AsMyVar3. Все остальные переменные имеют тип данных Variant. Т.е. если Вы не задаете каждой переменной свой тип хранимых данных явно(т.е. не указываете для неё тип данных через As), то VBA сам присваивает для такой переменной тип данных Variant, т.к. он может хранить любой тип данных. А вот так выглядит правильное присвоение типа данных:

Dim MyVar1 As Integer, MyVar2 As Integer, MyVar3 As Integer

Это и есть объявление переменных. Т.е. сначала идет оператор области действия (Dim, Public,Static), сразу за ним имя переменной, затем оператор As и тип.
Но это не все. Некоторые типы переменным можно присваивать еще короче — даже без оператора As:

Dim MyVar1%, MyVar2%, MyVar3%

Всего шесть типов, которые можно объявить подобным методом:
! — Single
# — Double
$ — String
% — Integer
& — Long
@ — Currency
На что стоит обратить внимание, при объявлении переменных подобным образом: между именем переменной и знаком типа не должно быть пробелов.
Я лично в большинстве статей предпочитаю использовать первый метод, т.е. полное указание типа. Это читабельнее и понятнее. В каких-то проектах могу использовать краткое указание, в общих(разработка в команде) — полное. В своих кодах Вы вправе использовать удобный Вам метод — ошибки не будет.

Теперь разберемся с операторами области действия(Dim, Public и Static):

  • Dim — данный оператор используется для объявления переменной, значение которой будет храниться только в той процедуре, внутри которой данная переменная объявлена. Во время запуска процедуры такая переменная инициализируется в памяти и использовать её значение можно внутри только этой процедуры, а по завершению процедуры переменная выгружается из памяти(обнуляется) и данные по ней теряются. Переменную, объявленную подобным образом еще называют локальной переменной. Однако с помощью данного оператора можно объявить переменную, которая будет доступна в любой процедуре модуля. Необходимо объявить переменную вне процедуры — в области объявлений(читать как первой строкой в модуле, после строк объявлений типа — Option Explicit). Тогда значение переменной будет доступно в любой процедуре лишь того модуля, в котором данная переменная была объявлена. Такие переменные называются переменными уровня модуля. Также для использования переменных во всех процедурах и функциях одного конкретного модуля можно использовать оператор Private. Но он в данном случае ничем не отличается от Dim, а пишется длиннее :) Плюс, Private нельзя использовать внутри процедуры или функции(только в области объявлений), что еще больше сужает её применимость. По сути чаще этот оператор применяется к функциям и процедурам(об этом см.ниже)
  • Static — данный оператор используется для объявления переменной, значение которой предполагается использовать внутри конкретной процедуры, но не теряя значения данной переменной по завершении процедуры. Переменные данного типа обычно используют в качестве накопительных счетчиков. Такая переменная инициализируется в памяти при первом запуске процедуры, в которой она объявлена. По завершении процедуры данные по переменной не выгружаются из памяти, но однако они не доступны в других процедурах. Как только Вы запустите процедуру с этой переменной еще раз — данные по такой переменной будут доступны в том виде, в котором были до завершения процедуры. Выгружается из памяти такая переменная только после закрытия проекта(книги с кодом).
  • Public — данный оператор используется для объявления переменной, значение которой будет доступно в любой процедуре проекта(в обычных модулях, модулях класса, модулях форм, модулях листов и книг). Переменная, объявленная подобным образом, должна быть объявлена вне процедуры — в области объявлений. Такая переменная загружается в память во время загрузки проекта(при открытии книги) и хранит значение до выгрузки проекта(закрытия книги). Использовать её можно в любом модуле и любой процедуре проекта. Важно: объявлять подобным образом переменную необходимо строго в стандартном модуле. Такие переменные называются переменными уровня проекта. В простонародье такие переменные еще называют глобальными(возможно из-за того, что раньше подобные переменные объявлялись при помощи оператора Global, который в настоящее время устарел и не используется).
    Для большего понимания того, где и как объявлять переменные уровня проекта два небольших примера.
    Неправильное объявление

    Option Explicit
     
    Sub main()
    Public MyVariable As String
    MyVariable = "Глобальная переменная"
    'показываем текущее значение переменной
    MsgBox MyVariable
    'пробуем изменить значение переменной
    Call sub_main
    'показываем измененное значение переменной
    MsgBox MyVariable
    End Sub
    'доп.процедура изменения значения переменной
    Sub ChangeMyVariable()
    MyVariable = "Изменили её значение"
    End Sub

    переменные не будут видны во всех модулях всех процедур и функций проекта, потому что:
    1. Оператор Public недопустим внутри процедуры(между Sub и End Sub), поэтому VBA при попытке выполнения такой процедуры обязательно выдаст ошибку — Invalid Attribut in Sub or Function.
    2. Даже если Public заменить на Dim — это уже будет переменная уровня процедуры и для других процедур будет недоступна.
    3. Т.к. объявление неверное — вторая процедура(ChangeMyVariable) ничего не знает о переменной MyVariable и естественно, не сможет изменить именно её.
    Правильное объявление

    'выше глобальных переменных и констант могут быть только декларации:
    Option Explicit     'принудительное объявление переменных
    Option Base 1       'нижняя граница объявляемых массивов начинается с 1
    Option Compare Text 'сравнение текста без учета регистра
    'глобальная переменная - первой строкой, выше всех процедур
    Public MyVariable As String
    'далее процедуры и функции
    Sub main()
        MyVariable = "Глобальная переменная"
        'показываем текущее значение переменной
        MsgBox MyVariable, vbInformation, "www.excel-vba.ru"
        'пробуем изменить значение переменной
        Call ChangeMyVariable
        'показываем измененное значение переменной
        MsgBox MyVariable, vbInformation, "www.excel-vba.ru"
    End Sub
    'доп.процедура изменения значения переменной
    Sub ChangeMyVariable()
        MyVariable = "Изменили её значение"
    End Sub

    Если при этом вместо Public записать Dim, то эта переменная будет доступна из всех функций и процедур того модуля, в котором записана, но недоступна для функций и процедур других модулей.
    Переменные уровня проекта невозможно объявить внутри модулей классов(ClassModule, ЭтаКнига(ThisWorkbook), модулей листов, модулей форм(UserForm) — подробнее про типы модулей: Что такое модуль? Какие бывают модули?)

  • Операторы области действия так же могут применяться и к процедурам. Для процедур доступен еще один оператор области действия — Private. Объявленная подобным образом процедура доступна только из того модуля, в котором записана и такая процедура не видна в диалоговом окне вызова макросов(Alt+F8)
  • 'процедура записана в Module1
    'эта процедура будет доступна для вызова исключительно из процедур в этом же модуле
    'но не будет доступна при вызове из других модулей
    Private Sub PrivateMain()
        MsgBox "Процедура может быть вызвана только из модуля, в котором записана", vbInformation, "www.excel-vba.ru"
    End Sub
    'другая процедура, записанная в этом же модуле
    Sub CallPrivate()
        Call PrivateMain
    End Sub
    'эта процедура записана в другом модуле - Module2
    'при попытке вызова этой процедурой получим ошибку
    ' Sub or Function not defined
    ' потому что процедура PrivateMain объявлена только для Module1
    Sub CallPrivate_FromModule1()
        Call PrivateMain
    End Sub

    При этом, если из Excel нажать сочетание клавиш Alt+F8, то в окне будут доступны только CallPrivate_FromModule1 и CallPrivate. Процедура PrivateMain будет недоступна.

Как правильно назвать переменную:

«Что самое сложное в работе программиста? — выдумывать имена переменным.» :-)А ведь придумать имя переменной тоже не так-то просто. Можно, конечно, давать им имена типа: a, d, f, x, y и т.д.(я сам иногда так делаю, но либо в простых кодах, либо для специального запутывания кода). Но стоит задуматься: а как Вы с ними будете управляться в большом коде? Код строк на 10 еще потерпит такие имена, а вот более крупные проекты — не советовал бы я в них оперировать такими переменными. Вы сами запутаетесь какая переменная как объявлена и какой тип данных может хранить и что за значение ей присвоено. Поэтому лучше всего давать переменным осмысленные имена и следовать соглашению об именовании переменных. Что за соглашение? Все очень просто: перед основным названием переменной ставится префикс, указывающий на тип данных, который мы предполагаем хранить в данной переменной. Про имеющиеся типы данных я уже рассказал выше. А ниже приведена примерная таблица соответствий префиксов типам данных:

Префикс Тип хранимых данных
b Boolean
bt Byte
i Integer
l Long
s Single
d Double
c Currency
dt Date
str String
obj Object
v Variant

Лично я немного для себя её переделал, т.к. некоторые обозначения мне кажутся скудными. Например Double я обозначаю как dbl, а Single как sgl. Это мне кажется более наглядным.

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

DefBool B
Sub test()
    Dim bCheck
End Sub

Автоматически переменной bCheck будет присвоен тип Boolean, т.к. она начинается с буквы b — регистр здесь не имеет значения(впрочем как в VBA в целом). Оператор Def задается в области объявления. Можно задать не одну букву, а целый диапазон букв:

DefBool B-C
Sub test()
    Dim bCheck, cCheck
End Sub

Но я считаю, что одной буквы для одного типа вполне достаточно. Можно задать сразу несколько операторов Def.

DefBool B
DefStr S
Sub test()
    Dim bCheck, sCheck
End Sub

Ниже приведен полный перечень операторов типов и данные, которые задает каждый из них:
DefBool — Задает тип Boolean
DefByte — Задает тип Byte
DefCur — Задает тип Currency
DefDate — Задает тип Date
DefDbl — Задает тип Double
DefInt — Задает тип Integer
DefLng — Задает тип Long
DefObj — Задает тип Object
DefSng — Задает тип Single
DefStr — Задает тип String
DefVar — Задает тип Variant
По умолчанию в VBA применена инструкция DefVar для всех букв(иначе говоря для всех переменных, которым не назначен тип данных явно через оператор As).

Ну и немаловажный момент это непосредственно осмысленное имя переменной. Имя переменной должно примерно отражать то, что в ней будет храниться. Например, Вы создаете отчет и Вам надо объявить две переменные: одна имя листа, другая имя книги. Можно было сделать так: str1, str2. Коротко, здорово. Но если подумать — и как можно понять, какая из этих переменных что хранит? Никак. Надо просматривать код и вспоминать, какой переменной какое значение было присвоено. Не совсем удобно, правда? А если бы Вы задали имена так: strBookName, strSheetName, то вроде как более понятно, что мы в них будем хранить. Это удобно не только вам самим при работе с кодом, но и другим людям, которые, возможно в будущем будут пользоваться Вашим кодом. Им будет удобнее читать код, если он будет оформлен грамотно, а переменные названы осмысленно. И не стоит экономить на длине имени — имя должно быть понятным. Без фанатизма, конечно :-). Хоть VBA и позволяет нам создавать переменные длиной до 254 символов, но читать такую переменную так же неудобно, как и с одним символом. Но здесь уже все зависит от Ваших предпочтений и фантазии.
Небольшое дополнение: лучше привыкать давать названия переменным на латинице(т.е. английский алфавит), т.к. для VBA английский язык «родной» и лучше использовать его.

Небольшой пример использования переменных в кодах:
Sub main()
'объявляем переменные с назначением конкретных типов
'As String - текст
'As Long   - целое число
Dim sAddress As String, sNewAddress As String, sShName As String
Dim lRow As Long
Dim rRange as Range 'назначили переменной тип ячейка/диапазон
 
'присвоили переменной rRange ссылку на текущую выделенную ячейку
Set rRange = Selection
'меняем выделение - выделяем ячейку D9
Range("D9").Select
'назначаем переменной адрес выделенных ячеек
sAddress = Selection.Address
'назначаем переменной lRow значение первой строки выделенной области
lRow = Selection.Row
'показываем сообщение
MsgBox "Адрес выделенной области: " & sAddress, vbInformation, "www.excel-vba.ru"
MsgBox "Номер первой строки: " & lRow, vbInformation, "www.excel-vba.ru"
'назначаем другой переменной значение адреса ячейки A1
sNewAddress = "A1"
'выделяем ячейку, заданную переменной sNewAddres
Range(sNewAddress).Select
MsgBox "Адрес выделенной области: " & sNewAddress, vbInformation, "www.excel-vba.ru"
'выделяем изначально выделенную ячейку, используя переменную rRange
rRange.Select
MsgBox "Адрес выделенной области: " & rRange.Address, vbInformation, "www.excel-vba.ru"
'задаем значение переменной
sShName = "excel-vba"
'переименовываем активный лист на имя, заданное переменной
ActiveSheet.Name = sShName
End Sub

Просмотреть пошагово выполнение данного кода поможет статья: Отлов ошибок и отладка кода VBA
Важно! Назначение значений переменным задается при помощи знака равно(=). Однако, есть небольшой нюанс: для переменных типа Object(а так же других объектных типов(Workbook, Worksheet, Range, Cells, Chart и т.п.)) присвоение идет при помощи ключевого оператора Set:

'присвоили переменной rRange ссылку на текущую выделенную ячейку
Set rRange = Selection

это так же называется присвоением ссылки на объект. Почему именно ссылки? Все просто: при помещении в переменную непосредственно ячейки или диапазона(Set var = Range(«A1») или Set rRange = Selection) нет никакого запоминания самой ячейки. В переменную помещается лишь ссылка на эту ячейку(можете считать, что это как ссылка в формулах) со всеми вытекающими: такое назначение не запоминает свойства ячейки до или после — в переменной хранится ссылка на конкретную ячейку и доступ есть исключительно к свойствам ячейки на текущий момент. Чтобы запомнить для этой ячейки значение, цвет или даже адрес (а так же и другие свойства) до её изменения и применить запомненное даже после изменения/перемещения самой ячейки — необходимо запоминать в переменные именно свойства ячейки:

Sub main()
    Dim val, l_InteriorColor As Long, l_FontColor As Long
    Dim rRange As Range 'назначили переменной тип ячейка/диапазон
 
    'присвоили переменной rRange ссылку на активную ячейку
    Set rRange = ActiveCell
    'запоминаем свойства ячейки
    val = rRange.Value                      'значение
    l_InteriorColor = rRange.Interior.Color 'цвет заливки
    l_FontColor = rRange.Font.Color         'цвет шрифта
    'копируем другую ячейку и вставляем на место активной
    ActiveSheet.Range("D1").Copy rRange
 
    'проверяем, что rRange теперь имеет совершенно другие свойста - как у D1
    MsgBox "Значение rRange: " & rRange.Value & vbNewLine & _
           "Цвет заливки rRange: " & rRange.Interior.Color & vbNewLine & _
           "Цвет шрифта rRange: " & rRange.Font.Color & vbNewLine, vbInformation, "www.excel-vba.ru"
 
    'назначаем свойства из сохраненных в переменных
    rRange.Value = val                      'значение
    rRange.Interior.Color = l_InteriorColor 'цвет заливки
    rRange.Font.Color = l_FontColor         'цвет шрифта
 
    'проверяем, что rRange возвращены параметры до копирования
    MsgBox "Значение rRange: " & rRange.Value & vbNewLine & _
           "Цвет заливки rRange: " & rRange.Interior.Color & vbNewLine & _
           "Цвет шрифта rRange: " & rRange.Font.Color & vbNewLine, vbInformation, "www.excel-vba.ru"
End Sub

Это так же распространяется на все другие объекты. Т.е. те переменные, значения которым назначаются через оператор Set.
Для других же типов Set не нужен и в переменную значение заносится без этих нюансов.


Константы

Так же есть и иной вид «переменных» — константы. Это такая же переменная, только(как следует из её названия) — она не может быть изменена во время выполнения кода, т.к. является величиной постоянной и значение её назначается только один раз — перед выполнением кода.

Const sMyConst As String = "Имя моей программы"

Константам могут быть назначены данные тех же типов, что и для переменных, за исключением типа Object, т.к. Object это всегда ссылка на объект, который как правило обладает «динамическими»(т.е. обновляющимися) свойствами. А изменение для констант недопустимо.
Для дополнительной области видимости/жизни констант используется только Public. Если область видимости не указана, то константа будет доступна только из того модуля, в котором объявлена. Здесь обращаю внимание на то, что Dim уже не используется, т.к. Dim это идентификатор только для переменных. Пару важных отличий объявления констант от объявления переменных:

  • при объявлении константы необходимо обязательно указывать явно, что это константа ключевым словом Const
  • сразу в момент объявления необходимо назначить константе значение: = «Имя моей программы»

Во всем остальном объявление и применение констант идентично объявлению переменных. Коротко приведу пару примеров.
Если константа объявлена внутри процедуры:

Sub TestConst()
    Const sMyConst As String = "Имя моей программы"
    MsgBox sMyConst 'показываем сообщение с именем программы
End Sub

то она не может быть использована в другой процедуре:

Sub TestConst()
    Const sMyConst As String = "Имя моей программы"
    MsgBox sMyConst 'показываем сообщение с именем программы
End Sub
Sub TestConst2()
    MsgBox sMyConst 'вызовет ошибку Variable not defined
End Sub

Чтобы использовать одну константу во всех процедурах модуля(того, в котором она объявлена), необходимо объявить её в области объявлений:

Const sMyConst As String = "Имя моей программы"
Sub TestConst()
    MsgBox sMyConst 'показываем сообщение с именем программы
End Sub
Sub TestConst2()
    MsgBox sMyConst 'уже не вызовет ошибку Variable not defined
End Sub

Чтобы использовать одну константу во всех процедурах проекта(книги), необходимо объявить её как Public:

Public Const sMyConst As String = "Имя моей программы"
Sub TestConst()
    MsgBox sMyConst 'показываем сообщение с именем программы
End Sub
Sub TestConst2()
    MsgBox sMyConst 'не вызовет ошибку Variable not defined, даже если процедура в другом модуле
End Sub

Подробнее можно прочитать выше — как я уже писал для констант применяются те же правила, что и для переменных.

Также см.:
Variable not defined или что такое Option Explicit и зачем оно нужно?
Что такое модуль? Какие бывают модули?
Что такое макрос и где его искать?
Отлов ошибок и отладка кода VBA


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

Понравилась статья? Поделить с друзьями:
  • Vba excel пауза в макросе
  • Vba excel переменную в буфер
  • Vba excel парсинг xml
  • Vba excel переменная эта книга
  • Vba excel пароль на код