Vba excel все форматы переменных

Справочная таблица по встроенным типам данных 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 вставлена


In a computer system, variables and data types are almost used in every program to store and represent data. Similarly, Excel VBA also has variables and data types to store and represent data and its type. In this article, we will learn about VBA variables, their scope, data types, and much more.

VBA Variables

VBA(Visual Basic for Application) variables are similar to other programming languages variables, they act as a container that is used to store data(integer, string, floats, etc). We can use the variables in the code at multiple places and executer the programs.

Defining Variables In VBA

VBA gives permission to define variables in two ways:

  1. Implicitly – In VBA, we can implicitly declare variables using the assignment(=) operator. All the variables that are implicitly declared in VBA are of type “Variant“. The variant type variables required more memory space than usual variables. Example: label=”gfg”
  2. Explicitly – Explicitly we can declare variables using “Dim” keyword. Explicit variable also reduces the naming conflicts and spelling mistakes. Example: Num as password

Syntax For VBA Variables

// macro definition

Sub VBA_Variable_Example ()

        Dim <name>

End Sub

VBA Variables Rule:

  1. Its length should be less than 255 characters.
  2. No space is allowed between characters.
  3. It should not starts with an integer.
  4. Period(.) is not allowed in between the characters.
Allowed Not Allowed
gfg_article gfg.article
dataStructureCourse1 1CourseDataStructure
geekforgeeks geeks for geeks

Example:

In this example, we will define a macro in excel, And we will enter the code inside that macro and execute the code to understand the working of VBA variables in excel.

Step 1: First, we will make our Developer option available in the Excel toolbar. For this, go to any of the tools(here, we are choosing Draw) and then right-click on it and select the “Customize the Ribbon..” option.

Customize-the-Ribbon

The excel will open pop-up options, there we need to check the Developer checkbox and click on OK. This will enable the Developer option and make it available in the excel top toolbar.

Developer-Option

Step 2: In this step, we will declare our variable in the visual basic editor. For this go to Developer > Visual Basic Editor.

Open-VBA-Editor

This will open the Visual Basic Code Editor, where we are required to write our VBA script.

Visual-Basic-Editor

Step 3: In this step, we will write our VBA scripts. For this, we will double click on ThisWorkbook under Microsoft excel objects in the left pan and open the editor and write the following code to it.

Sub VBA_Variable_GFG_Example()

Range(“a1”).Value = “Data Structure Course”

Range(“b1”).Value = “Data Structure Course”

Range(“c1”).Value = “Data Structure Course”

Var = “Data Structure Course”

Range(“a3”).Value = Var

Range(“b3”).Value = Var

Range(“c3”).Value = Var

End Sub

In the above, we can see without using variables if we want to make changes to the string “Data Structure Course” and add “GeeksForGeeks” before every string, we need to repeat it at three different places. But if we use a variable then we just need to change it at one place where we declare our variable. This will reduce the workload.

Sub VBA_Variable_GFG_Example()

Range(“a1”).Value = “Data Structure Course”

Range(“b1”).Value = “Data Structure Course”

Range(“c1”).Value = “Data Structure Course”

Var = “GeeksForGeeks – Data Structure Course”

Range(“a3”).Value = Var

Range(“b3”).Value = Var

Range(“c3”).Value = Var

End Sub

We will write this code in the VBS script editor and execute it. This will print the output string in the cells defined in the code.

VBA-Script

Once, we execute it using the Run button, we will get the following output.

Output

Scope Of VBA Variables

The scope of variables is determined when we declare the variable. In VBA, the scope tells where the variable may be used. There is three level of scopes of the variable:

1. Procedure Level: These are those variables that can be used within the procedure they are defined. A Procedure is either a Sub or a Function

Example: In this example, we will see the procedure level of the VBA variable’s scope. For this open the VBA editor and write the following code to it.

Sub sub1()

Dim res As String

res = “The variable which can be used within the procedure they are defined in.”

Range(“a1”).Value = res

End Sub

Procedure-Level-Scope

Once, we click on the Run button in the VBA editor, we will the output. The text will get printed to cell A1.

Final-output

2. Module Level: It is also known as the Private Module Level. It can be used by any procedures within the same module. These variables must be declared outside of all the procedures, at the top of the module.

Example: In this example, we will look for the module scope of variables. For this, we will create a new module. We will open VBA Editor and in the left pane (project explorer) we will Right-Click and create a new module add the following code to it.

Dim txt As String

Sub ProcedureDemo()

txt = “A Sub or Function is a Procedure, variables defined inside them only accessible within them”

Range(“a1”).Value = txt

End Sub

Sub PrivateModuleDemo()

txt = “Variable which is define inside a module, are accessible by all the procedures within that module”

Range(“a2”).Value = txt

End Sub

Module-Level

After this, we just need to click on the Run button. Also, when we run it, it asks for which macros to run, there we need to choose “Macros In: <All Projects>“.

Macros-In

 Once we run it, we will get the output in cells A1 and A2. 

Final-output

3. Public Module Level: As the name suggests, the public module variables scope is at the Project level. If we define any variable as a public module variable it can be used in any module inside that project.

Example: In this example, we will add two different modules and define a public VBA variable inside one module and try to access it from both modules. Below is the code for module1 and module2.

Module1

Public res As String

Sub demo_1()

res = “geeks”

Range(“a1”).Value = res

End Sub

Module2

Sub demo_2()

res = “geeksforgeeks”

Range(“a2”).Value = res

End Sub

Once, done with both the modules. Just click on the Run button. The output will get printed in cells A1 and A2,

Click-on-the-Run-button

Fig 12 – Output

Lifetime Of Variable

The variables can retain their value up to their scope. The lifetime of a variable tells about how long a variable can retain its value. In order to extend the scope and so, the lifetime of a variable we need to declare the variable with a static keyword. If we declare a variable with a static keyword, the variables will retain their value even after all the macros are finished execution.

Example: In this example, we will define a variable using the static keyword and execute it multiple time to check whether it retains the value or not. We need to write the following code to the VBA Editor.

Sub StaticVariableDemo()

Static count As Integer

count = count + 1

MsgBox (count)

End Sub

After this, we need to execute it. Every time we will click on the run button the MessageBox will return the updated value. (1, 2, 3…..) and thus it will extend its scope and lifetime.

Final-output

VBA Data Types

In computers, we use data types to differentiate between the integers and strings, etc. The data types which we will assign to a variable, decide what should be stored in that variable, i.e., the values that need to be stored in the variable is depends on the data type of the variable. In VBA, data types are divided into two major types:

1. Numeric Data Type: Numeric data types are used to perform mathematical operations such as addition, subtraction, etc. It is used to handle the numbers in various representations format. In numeric data type, the Integral Type represents only the whole numbers(zero, positive & negative). Non-Integral Types represent both the integer and the fractional part.

Data Types Memory Size Value Range
Byte 1 2yte 0 to 255
Integer 2 bytes -32,768 to 32,767
Long 4 bytes -2,147,483,648 to 2,147,483,648
Single 4 bytes Negative Values (-3.402823E+38 to -1.401298E-45) & Positive Values (1.401298E-45 to 3.402823E+38)
Double 8 bytes Negative Values (-1.79769313486232e+308 to -4.94065645841247E-324) & Positive Values (4.94065645841247E-324 to 1.79769313486232e+308)
Currency 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807
Decimal 12 bytes No Decimal Places (+/- 79,228,162,514,264,337,593,543,950,335) & Up to 28 Decimal Places (+/- 7.9228162514264337593543950335)

2. Non-Numeric Data Type: Non-Numeric data types are not manipulated by the arithmetic operators. These are comprised of texts, data, etc.

Data Types Memory Size Value Range
String(fixed size/length) Equivalent to String’s length(in bytes) 1 to 65,400 characters
String(variable length) String’s length + 10 bytes 0 to 2 billion characters
Boolean 2 bytes True/False
Object 4 bytes Embedded object
Data 8 bytes January 1, 100 to December 31, 9999
Variant(numeric) 16 bytes Any value
Variant (text) Text’s length + 22 bytes 0 to 2 billion characters

Note: If we do not declare any data type, the VBA will be default makes variable as a variant type.

Example:

In this example, we will write a simple script to create a button and with one click of that button an event will occur and we will get the output.

Step 1: First we will insert a command button in our excel worksheet. For this go to Developer > Insert > Command Button and click on it.

Click-on-the-command-button

Fig 14 – Command Button

 After that, we can insert the button anywhere in the sheet we want. We just need to drag it over the excel sheet.

 Command-Button-View

Step 2: In this step, we will write the script for our button. For this just double-click on the button. This will open the VBA Script Editor where we will write the following code. In the below code, we are defining GFG and course as String data type and res as Integer data type.

Private Sub CommandButton1_Click()

Dim GFG As String, res As Integer, course As String

GFG = “GeeksForGeeks”

res = “01”

course = “Interview Preparation”

Range(“a1”).Value = GFG

Range(“b1”).Value = res

Range(“c1”).Value = course

End Sub

VBA-Script-For-Button

Step 3: In this step, we will save our script. For this click on the Save button in the VBA Editor. 

Saving-VBA-Button-Script

The excel will popup a window asking for saving the macros. We need to click “Yes” and it will save it.

Saving-Macro-To-Workbook

Step 4: Now, we will execute our script. For this, we need to click over the command button. But before clicking over it, we are required to come out of Design Mode. To move out of any mode just click on mode once.

Moving-Out-Of-Design-Mode

Once we are done with this, we will execute our script by clicking over the commandButton1. It will give the following output.

Final-Output

Note: If we write “01” in any cell in excel, it will print “1” by default. That’s why the in output, in cell b1 only “1” is printed.

In this Article

  • VBA Data Types – Variables and Constants
    • What is a Variable?
    • The Different Common Data Types Available in VBA
    • Table of All The VBA Data Types
    • Using the Variant Data Type
    • Using Option Explicit in VBA
    • Using Variables in Your Code
    • What is a Constant?

VBA Data Types – Variables and Constants

This VBA Tutorial will help you understand the concept of what variables and constants are. These are important to know for all programming languages and not just VBA.
If you want to start learning to program, then you have to understand what variables and constants are and how to use them in your code.

What is a Variable?

A variable is a value, that you declare in your code and consequently it is reserved in your computer’s memory and stored. You have to name your variable and it’s good practice to declare the data type of your variable. When you declare the data type, you are telling the program, the type of data that needs to be stored by your variable.

You will use the variable in your code, and the program will also access your variable. The actual value of your variable can change while your code is running.

In VBA, we have to use a Dim statement in order to declare a variable. The way to declare a variable in VBA is shown in the code below:

Sub DeclaringAVariable()

Dim product_Name As String
Dim number_of_Products as Integer

End Sub

Once you’ve made your declaration statement, you can initialize your variable, since declaring a variable just reserves space in the memory of your computer. When you initialize your variable you assign an initial value for your variable. The way to initialize a variable in VBA is shown in the code below:

Sub InitializingAVariable()

Dim number_of_Products As Integer
number_of_Products = 5000

End Sub

In terms of how to name your variable in VBA, you need to ensure that:

• It is not a reserved keyword. VBA has certain reserved keywords such as Dim, Private, Function, Loop and other keywords that you will use in your code and you cannot name your variable after a keyword.
• You don’t use special characters such as !, @, &, ., # or spaces when naming your variables.
• The name of your variable cannot be more than 255 characters in length.
• You also cannot start a variable name with a number.

The Different Common Data Types Available in VBA

There are many data types you can use in VBA. However, there are common ones that you will find yourself using for the most part in your code. These are:

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

Note: When you store a value in a String data type, you have to use quotation marks. For example:

Dim product_Name as String
product_Name = “ABC Product”

Note: When you store a value in a Date data type, you have to use quotation marks. For example:

Dim start_date as Date
start_date = “1/4/2019”

Table of All The VBA Data Types

Data Type Stored Range of Values
Byte 1 Byte 0 to 255
Integer 2 Bytes -32,768 to 32,767
Single 4 Bytes -3.402823E38 to -1.401298E-45 for negative values, 1.401298E-45 to 3.402823E38 for positive values
Long 4 Bytes -2,147,483,648 to 2,147,483,648
Double 8 Bytes -1.79769313486232e+308 to -4.94065645841247E-324 for negative values, 4.94065645841247E-324 to 1.79769313486232e+308 for positive values.
Decimal 14 Bytes +/-79,228,162,514,264,337,593,543,950,335 for no decimal points,+/-7.9228162514264337593543950335 for 28 places to the right of the decimal
Date 8 Bytes January 1, 100 to December 31, 9999
Currency 8 Bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807
String (variable length) 10 bytes added to the string length 0 to 2 billion characters
String (fixed length) string length 1 to approximately 65,400
Object 4 Bytes Object in VBA
Boolean 2 Bytes True or False

Using the Variant Data Type

If you’re not sure about the data type of your variable or it’s likely to need to change, then you can use the variant data type.
The variant data type can store any kind of data except the fixed-length String data type. You declare the variant data type in the following way:

Dim myValue as Variant

Using Option Explicit in VBA

When you use Option Explicit in VBA, this means you have to declare all your variables which is a good idea to do. You can ensure Excel always automatically adds Option Explicit in the VBE by going to Tools>Options>Editor and then check Require Variable Declaration.

VBA Option Explicit

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

Using Variables in Your Code

The example below illustrates all the concepts we covered above:

Sub UsingVariablesInYourCode()

Dim product_Name As String
product_Name = "ABC Product"
MsgBox product_Name

End Sub

The result is:

Message Box showing Product Name

What is a Constant?

A constant is similar to a variable but it stores a value that cannot change. The way to declare a constant in VBA is shown in the code below:

Sub DeclaringAConstant()
 
Const NumberofDays = 1
MsgBox NumberofDays
 
End Sub

The result is:

Declaring a Constant

Note: You can declare a constant as Private which means you can use it in its own module only or you can declare a constant as Public which means you can use it in other modules.

Переменные, типы данных и константы

Главное предназначение VB А — обработка данных. Некоторые данные сохраняются в объек­тах, например, диапазонах рабочих листов. Другие данные хранятся в созданных вами переменных.

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

Переменные могут содержать данные разных типов — от простых логических, или бу­левых, значений ( True или False ) до больших значений с двойной точностью (см. следующий раздел).

Значение присваивается переменной с помощью оператора равенства (подробнее об этом — далее в главе).

VBA поддерживает несколько огра­ничений в именовании переменных:

  • Можно использовать в названиях символы букв, числа и некоторые знаки препи­нания, но первой в имени переменной всегда должна вводиться буква.
  • VBA не различает регистры.
  • Нельзя использовать в именах пробелы или точки.
  • Чтобы сделать имена переменных удобочитаемыми, используют смешанный регистр (например, InterestKate , а не interestkate ) или вводят символ подчеркивания ( lnterest _ Rate ).
  • Специальные символы объявления типов (#, $, %, & или !) не применяются в имени переменной.
  • Названия переменных ограничены длиной 254 символов.
  • Не допускается применять в качестве названий переменных или процедур зарезервированные слова, т.е. такие слова, которые используются VBA .

Определение типов данных

  • Тип данных указывает, в каком виде данные хранятся в памяти: как целые значения, дей­ствительные числа, текст н т.п.
  • VBA может автоматически типизировать данные, что приводит к медленному выполнению операций и не эффективному использованию памяти.
  • При явном объявлении типа данных всех используемых пе­ременных VBA может выполнять дополнительную проверку ошибок на эта­пе компиляции.
  • При явном объявлении типа данных программа работает быстрее и занимает меньше места в оперативной памяти.
  • Чтобы обеспечить обязательное объявление всех используемых переменных, необходимо включить строку
    Option . Explicit
    в качестве первой инструкции в модуле VBA .

В таблице перечислены поддерживаемые в VBA типы данных

Тип данных

Резервируется байт

Наименьшее значение

Наибольшее значение

Byte

1

0

255

Boolean

2

False (Ложь)

True (Истина)

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,94065645341247Е-324

4,94065645841247Е-324

1,79769313486232Е308

Currency

8

-922337203685477,5808

922337203685477,5807

Decimal

14

+/-79228162514264337593543950335 без десятичных знаков

+/-7,9228162514264337593543950335 с 28-ью знаками после запятой

Date

8

1 января 100 года

31 декабря 9999 года

Object

4

Любая ссылка на объект

string (пере­менной длины)

10 байт + длина строки

0

приблизительно 2 млрд

string (фикси­рованной длины)

Длина строки

1

65400

Variant (числа)

16

Любое числовое значение в рамках диапазона типа данных Double

Variant (сим­волы)

22 байта + длина строки

0

приблизительно 2 млрд

Пользовательский

Зависит от типа

Зависит от элемента

  • Чтобы в тексте программы распознать тип данных переменной или константы можно использовать стандартную приставку (префикс) в нижнем регистре в названии переменной в соответствии с приведенной таблицей.

Префикс

Тип данных

b

Boolean

i

Integer

l

Long

s

Single

d

Double

с

Currency

dt

Date / Time

str

String

obj

Object

v

Variant

u

Пользовательский

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

  • Если для переменной, используемой в процедуре VBA , не объявлен тип данных, то, по умолчанию, будет задан тип данных Variant .
  • Данные, которые хранятся в Variant , изменяют свой тип, в зависимости от того, ка­кие операции над ними выполняются.
    Пример 1 .

Sub VariantDemo ()

MyVar = «123»

MyVar = MyVar / 2

MyVar = «Ответ: » & MyVar

MsgBox MyVar

End Sub

  • При обработке типа дан­ных Variant могут возникнуть проблемы.
    Пример 2 . Какое сообщение выдаст следующая процедура?

Sub VariantDemo 2()

MyVar = «123»

MyVar = MyVar + MyVar

MyVar = «Ответ: » & MyVar

MsgBox MyVar

End Sub

Функция определения типа данных

Для определения типа данных переменной используется функция VBA TypeName .

Пример 1.

Sub VariantDemo2()

MyVar = «123»

MsgBox TypeName(MyVar)

MyVar = MyVar / 2

MsgBox TypeName(MyVar)

MyVar = «Ответ: » & MyVar

MsgBox TypeName(MyVar)

MsgBox MyVar

End Sub

Тестирование явного объявления типов данных

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

Sub TimeTestU

Dim x As Integer, у As Integer

Dim A As Integer, В As Integer, С As Integer

Dim i As Integer, j As Integer

Dim StartTime As Date, EndTime As Date

‘ Сохранение времени начала вычислений

StartTime = Timer

‘ Выполнение вычислений

х = 0

у = 0

For i = 1 То 5000

For j = 1 То 1000

А = х + у + i

В = у — х — i

С = х — у — i

Next j

Next i

‘ Получение времени окончания вычислений

EndTime = Timer

‘ Отображение общего времени

MsgBox Format(EndTime – StartTime)

End Sub

Задача.

Сравните время выполнения этой программы и время выполнения этой же программы при превращении операторов Dim в комментарии.

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

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

Область действия

Способ объявления переменной

Отдельная процедура

В процедуру включается оператор Dim или static

Отдельный модуль

Перед первой процедурой в модуле вводится оператор Dim или private

Все модули

Перед первой процедурой в модуле вводится оператор Public

Локальные переменные

  • Локальная переменная — это переменная, объявленная в процедуре.
  • Локальные перемен­ные могут использоваться только в процедуре, в которой они объявлены.
  • После выполнения процедуры переменная становится невостребованной, поэтому Excel освобождает соответст­вующую область памяти.
  • Если требуется сохранить значение переменной, объявите ее как static .
  • Чтобы объявить локальную переменную — вставьте оператор Dim между операторами Sub и End Sub .
  • Dim – сокращение от Dimension (Размерность). В старых версиях BASIC этот оператор использовался исключительно для объявления размерности массива.
  • Другой способ указания типа данных для переменной : язык VBA позволяет присоединить символ к на­званию, чтобы указать ее тип данных.
    Пример, можно объявить пере­менную MyVar как целое число, добавив к ее названию символ %: Dim MyVar %
  • Символы объявления типов данных представлены для большинства типов данных VBA (отсутствующие в таблице типы данных не имеют собственного символа объявления типа).

Тип данных

Символ объявления типа

Integer

%

Long

&

Single

!

Double

#

Currency

@

String

S

•  Локальные переменные позволяют экономно использовать память, так как VBA освобождает память, которую они используют, после окончания выполнения процедуры.

Переменные уровня модуля

Иногда необходимо, чтобы переменная была доступна во всех процедурах модуля. В та­ком случае объявите переменную перед первой процедурой модуля (за пределами процедур или функций).

В приведенном ниже примере оператор Dim — первая инструкция в модуле. Обе проце­дуры MySub и YourSub имеют доступ к переменной CurrentValue .

Dim CurrentValue As Integer

Sub MySub{)

‘ -[Здесь вводится текст процедуры] —

End SUb

Sub YourSub()

‘-[Здесь вводится текст процедуры] —

End Sub

Значение переменной уровня модуля не изменяется при окончании выполнения процедуры.

Переменные Public

Чтобы сделать переменную доступной во всех процедурах всех модулей VBA в проекте, необ­ходимо объявить переменную на уровне модуля с помощью ключевого слова Public перед первой процедурой модуля, например, так:

Public CurrentRate as Long

Код объявления пере­менных Public должен вводиться в стандартном модуле VB А, а не в коде модуля листа или формы.

Переменные Static

Переменные Static — особый случай. Они объявляются на уровне процедуры и сохра­няют свое значение после окончания процедуры.

Sub MySub()

Static Counter As Integer

‘-[Здесь вводится текст процедуры] –

End Sub

Работа с константами

Константа – имено­ванное значение или строка, которая не меняется при выполнении программы.

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

Константы объявляются с помощью оператора Const .

Примеры :

Const NumQuarters as Integer = 4

Const Rate = .0725, Period = 12

Const ModName as String = «Budget Macros»

Public Const AppName as String = «Budget Application»

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

Константы имеют область действия как и переменные.

Область действия

Способ объявления константы

Отдельная процедура

В процедуре или функции

Отдельный модуль

Перед первой процедурой в модуле

Все модули

Перед первой процедурой в модуле с ключевым словом Public

При попытке изменить значение константы в процедуре VBA вы получите ошибку.

Использование предопределенных констант

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

В сле­дующей процедуре для изменения ориентации страницы активного листа на альбомную при­менена встроенная константа ( xlLandscape ):

Sub SetToLandscape()

ActiveSheet.PageSetup.Orientation = xlLandscape

End Sub

Константу xlLandscape можно обнаружить путем записи макроса.

Описание констан­т можно найти в справочной системе.

Если включен параметр AutoList Members , то можно получить помощь непосредственно при вводе кода. Во многих случаях VBA автоматически перечисляет все константы, присваиваемые опреде­ленному свойству.

Управление строками

В VBA представлено два типа строк.

  • Строки фиксированной длины объявляются с определенным количеством символов. Максимальная длина строки составляет 65535 символов.
  • Строки переменной длины теоретически могут вмещать до 2 млрд. символов.

Память для строки отводится из расчета 1 байт на каждый символ и для хранения заголовка строки.

В следующем примере переменная MyString объявляется как строка с максимальной длиной 50 символов. YourString тоже объявлена как строка, но она имеет переменную

длину:

Dim MyString As String * 50

Dim YourString As String

Работа с датами

Переменная, определенная как Date , занимает 8 байт памяти и может содержать даты в диапазоне от 1 января 100 года до 31 декабря 9999 года.

В VBA дата и время определяются как значения, заключенные между знаками # (см. далее).

Ошибка дат в Excel

В Excel используется неправильное предположение, что 1900 год – високосный.

В ячейке с формулой =ДАТА(1900;2;29) появится значение 29 февраля 1900 года.

Функция DateSerial (190 Q ,2,29) в VBA возвратит 1 марта 1900 года (!).

Операторы присвоения

Оператор присвоения — это инструкция VBA , выполняющая математическое вычисление и присваивающая результат переменной или объекту.

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

В VBA оператором присвоения выступает знак равенства (=).

Примеры использования операторов присвоения (выражения приводятся справа от знака равенства):

х = 1

X = X + 1

х = ( у * 2) ! ( г * 2) FileOpen = True FileOpen = Not FileOpen Range С «The Year»).Value = 2001

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

Зачастую в выражениях применяются функции. Это могут быть встроенные функции VBA , функции рабочих листов Excel или специальные функции, разработанные в VBA .

Булевы операторы VBA

Таблица. Булевы операторы VBA

Оператор

Действие

not

Логическое отрицание выражения

And

Логическая конъюнкция двух выражений

Or

Логическая дизъюнкция двух выражений

xoR

Логическое отрицание двух выражений

Eqv

Логическая эквивалентность двух выражений

imp

Логическая импликация двух выражений

Примеры.

  1. Свойство DisplayGridLines принимает значение True или False . Следовательно, применение оператора Not изменяет True на False , a False — на True :
    ActiveWindow . DisplayGridLines = _
    Not ActiveWindow . DisplayGridLines
  2. Представленное далее выражение осуществляет логическую операцию And . Оператор MsgBox отображает True , только если Лисг1 — активный лист и активная ячейка находит­ся в строке 1. Если одно или оба этих условия неверны, оператор MsgBox отображает False :
    MsgBox ActiveSheet . Name = «Лист1» And ActiveCell . Row = 1
  3. Следующее выражение осуществляет логическую операцию Or . Оператор MsgBox отображает True , если активен лист Лист1 или Лист2:
    MsgBox ActiveSheet.Name = » Лист 1″ Or ActiveSheet.Name = » Лист 2″

Массивы

Массив — это именованная группа проиндексированных элементов одного типа. На конкретный элемент массива ссылаются, используя имя массива и индекс. Например, массив MonthNames из 12-ти строк (каждая переменная соответствует названию месяца). Можно обратиться к первому элементу массива как
MonthNames(0), ко второму — как MonthNames(1) и т.д., до MonthNames(11).

Одномерные массивы

Массив объявляется с помощью операторов Dim или Public . Можно определить количество элементов в массиве: введите первый индексный номер, ключевое слово То и последний индексный номер — вся конструкция будет заключена в скобки. Например, так можно объявить массив, содержащий ровно 100 целых чисел:
Dim MyArray(1 To 100) As Integer

Многомерные массивы

Массивы VBA могут иметь до 60-ти измерений. Показанный ниже оператор объявляет двухмерный 100-элементный массив целых чисел:
Dim MyArray(1 To 10, 1 То 10) As Integer

Так присваивается значение элементу предыдущего массива
МуАггау(1, 4) = 125

Трехмерный массив
Dim MyArray(1 To 5, 1 То 6, 1 То 7) As Integer
состоит из 420 чисел типа Double.

Динамические массивы

Динамический массив не имеет предопределенного количества элементов. Динамический массив объявляется с незаполненными значениями в скобках:

Dim MyArray () As Integer

Перед использованием динамического массива необходимо обратиться к оператору
ReDim , указывающему VBA , сколько элементов находится в массиве
или
ReDim Preserve , если решено сохранить текущую длину массива.

Оператор ReDim можно использовать сколько угодно раз, изменяя, если требуется, размер массива.

Переменные объектов

Переменная объекта — это переменная, представляющая целый объект, например, диапазон или рабочий лист. Переменные объектов имеют особое значение по двум причинам:

¦ значительно упрощают программу;

¦ ускоряют выполнение программы.

Переменные объектов, как и обычные переменные, объявляются с помощью оператора Dim или Public . Например, в следующем операторе переменная inputArea объявляется как объект Range : Public InputArea As Range

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

Sub KoObjVar()

Worksheets(» Лист 1″).Range(«Al»).Value =124

Worksheets(» Лист 1″).Range(«Al»).Font.Bold = True

Worksheets(» Лист 1″).Range(«Al»).Font.Italic = True

End Sub

Эта процедура вводит значение в ячейку А1 листа Лист1 активной рабочей книги, а затем делает шрифт содержимого ячейки полужирным и курсивным. В примере введено довольно много кода для такой простой операции. Чтобы пощадить себя, сведите процедуру к исполь­зованию объектной переменной:

Sub ObjVar()

Dim MyCell As Range

Sec MyCell = Worksheets(» Лист 1″).Range(«Al»)

MyCell.Value =124

MyCell.Font.Bold = True

MyCell.Font.Italic = True

End Sub

После объявления переменной MyCell как объекта Range оператор Set присваивает ей сам объект. В результате в следующих операторах используется упрощенная ссылка MyCell вместо длинной Worksheets (» Лист1″) . Range(» Al «).

Пользовательские типы данных

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

Type Customerlnfo
Company As String * 25
Contact As String * 15
RegionCode As Integer
Sales As Long
End Type

Пользовательские типы данных определяются вверху модуля перед началом

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

Dim Customers ( 1 To 100) As Customerlnfo

Все 100 элементов этого массива состоят из четырех компонентов (как указано в пользовательском типе данных— Customerlnfo ). Вы можете сослаться на конкретный компонент элемента :

Customers(5).Company = «Acme Tools»

Customers(1).Contact = «Tim Robertson»

Customers(1).RegionCode = 3

Customers(1).Sales = 150677

Чтобы скопировать информацию из Customers (1) в Customers ( 2 ), используется следующая инструкция:

Customers (2) = Customers (1)

Предыдущий пример эквивалентен приведенному далее блоку инструкций:

Customers(2).Company = Customers(1).Company

Customers(2).Contact = Customers(1).Contact

Customers(2}.RegionCode = Customers(1).RegionCode

Customers(2).Sales = Customers(1).Sales

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.

Понравилась статья? Поделить с друзьями:
  • Vba excel все свойства ячейки
  • Vba excel все свойства кнопки
  • Vba excel все прописные
  • Vba excel все об msgbox
  • Vba excel все буквы строчные