Справочная таблица по встроенным типам данных 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:
2. Отметьте галочкой опцию Require Variable Declaration на вкладке Editor:
3. Теперь новый модуль открывается со строкой Option Explicit:
In this Article
- Variant Variable Type
- Declare Variant Variable at Module or Global Level
- Module Level
- Global Level
- Using a Variant to populate Excel
- Declaring a Dynamic Array
Variant Variable Type
A Variant Variable can hold any time of data (string, integers, decimals, objects, etc.). If you don’t declare a variable type, your variable will be considered variant.
To declare an Variant variable, you use the Dim Statement (short for Dimension):
Dim varName as Variant
Dim rng as Variant
Then, to assign a value to a variable, simply use the equal sign:
varName = "John"
rng = Sheets(1).Range("A1")
Putting this in a procedure looks like this:
Sub strExample()
'declare the variants
Dim strName As Variant
Dim rng As Variant
'populate the variables
strName = "Fred Smith"
Set rng = Sheets(1).Range("A1")
'populate the sheet
rng.Value = strName
End Sub
If you run the code above, cell A1 in Sheet 1 will be populated with “Fred Smith”
By the names declared above, we could conclude that the varName would contain text, and the objSheet would contain a worksheet object. But actually, any type of data can be directed to the variable.
You could populate the variables declared above as follows and no error would occur.
varName = 6
objSheet - "Fred"
It is unusual to use variant variables and not considered good practice. On occasions, however, Variant variables are useful.
Declare Variant Variable at Module or Global Level
In the previous example, you declared the Variant variable within a procedure. Variables declared with a procedure can only be used within that procedure.
Instead, you can declare Variant variables at the module or global level.
Module Level
Module level variables are declared at the top of code modules with the Dim statement.
These variables can be used with any procedure in that code module.
Global Level
Global level variables are also declared at the top of code modules. However, instead of using the Dim statement, you use the Public statement to indicate that the string variable is available to be used throughout your VBA Project.
Public strName as Variant
If you declared the variant variable at a module level and used in a different module, an error would occur.
If you had used the Public keyword to declare the variant variable, the error would not occur and the procedure would run perfectly.
Using a Variant to populate Excel
Consider the following procedure:
Sub TestVariable
'declare a string to hold the product name
Dim strProduct as string
'declare an integer to hold the product quantity
Dim iQty as integer
'declare doubles to hold the product price, and total price
Dim dblPrice as Double
Dim dblTotal as Double
'populate the variables
strProduct = "All Purpose Flour"
iQty = 3
dblPrice = "$5.00"
dblTotal = "$15.00"
'populate the Excel sheet
Range("A1") = strProduct
Range("A2") = iQty
Range("A3") = dblPrice
Range("A4") = dblTotal
End Sub
When we run this code, the following error occurs.
Click Debug
You cannot put a dollar sign into the variable as the variable is declared as a Double, and therefore cannot store string values.
Declare dblPrice and dblTotal as Variants which means you are not restricted to a data type.
Dim dblPrice as Variant
Dim dblTotal as Variant
Re-run the code and the data will appear in the Excel sheet as it should.
Note that the data entered in A4 and A5 are automatically then converted by Excel to numbers.
Declaring a Dynamic Array
Variant variables are also useful when you are declaring a dynamic array as they allow the size of the array to change during run-time.
With a Variant Array, you do not need to define the array size. The size will automatically adjust.
Sub VariantArray()
Dim arrList() As Variant
'Define Values
arrList= Array(1, 2, 3, 4)
'Change Values
arrList= Array(1,2,3,4,5,6)
'Output Position 4
MsgBox arrVar(4)
End Sub
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!
Learn More!
Excel VBA Variant Data Types
In VBA, we have different types of Variable data types. We use them when we need to specify some certain kind of input to be given. Suppose, for the whole number we use Integer, for the text we use String and for lengthy data set we use Long data type. And there are some more data types that we use different types of variable declaration. But what if I tell you that we can define all these variables in a single Data type. For that purpose, we have VBA Variant where we can define any type of variable which we want.
VBA Variant is as easy as using other data types. For defining any kind of variable use any name or alphabet to name it and then we choose data type which we want. Let’s see an example where we will see how a variable can be declared using Integer data type.
As we can see in the above screenshot, for Integer data type variable, we can use number ranging from -32768 to +32767. But if we choose a variant here instead of Integer, then it will work same as Integer but there will not be any limit as data type Variant consists of all kind of variable formation in it.
And Variant can be used as shown below.
How to Declare Variant Data Type in Excel VBA?
We will summarize the whole process of declaring variables in VBA by using VBA Variant. Let’s see an example where we will use traditional data types for declaring variables first.
You can download this VBA Variant Excel Template here – VBA Variant Excel Template
Steps to Declare Variant Data Type
Follow the below steps to declare Variant Data Type in Excel by using VBA code.
Step 1: Go to the VBA window, under the Insert menu tab select Module as shown below.
Step 2: Now write the subprocedure for VBA Variant in any name as you want. We have used the name which can define the process which uses.
Code:
Sub VBA_Variant1() End Sub
Step 3: Now define a variable where we can store or print any kind of text or name. For that, we need to use a string data type.
Code:
Sub VBA_Variant1() Dim Name As String End Sub
Step 4: Now define another variable where we can store or print any data. For that, we will again use a String data type.
Code:
Sub VBA_Variant1() Dim Name As String Dim DoB As String End Sub
Step 5: Now define another variable where we can store some numbers. For that, we will use an integer data type.
Code:
Sub VBA_Variant1() Dim Name As String Dim DoB As String Dim Age As Integer End Sub
Step 6: And at last, we will declare another variable where we will be storing lengthy number using datatype Long
Code:
Sub VBA_Variant1() Dim Name As String Dim DoB As String Dim Age As Integer Dim RollNo As Long End Sub
So basically here, we will be creating a database which will be having the name of a student, Date of Birth, Age, and Roll No. Now to complete this process, we will assign the values to each of the variables which we defined above.
Step 7: So we will declare the name of the student as Ashwani whose date of birth is 02 Sept 1990 and age is 29 and whose roll number is 16238627 in his certification exam as shown below.
Code:
Sub VBA_Variant1() Dim Name As String Dim DoB As String Dim Age As Integer Dim RollNo As Long Name = "Ashwani" DoB = "02-09-1990" Age = 29 RollNo = 16238627 End Sub
Please note, the value where we will use String data type are quoted in inverted commas as they as in Text. Now to print these values we can use Msgbox or Debug.Print.
Debug print is the best way here, as we have multiple values for which if we use Msgbox then we need to use separated msgbox to see the output. So, to avoid that, we will use Debug.Print
Step 8: Use Debug.Print function and write all the variable which we defined above separated by Commas as shown below.
Code:
Sub VBA_Variant1() Dim Name As String Dim DoB As String Dim Age As Integer Dim RollNo As Long Name = "Ashwani" DoB = "02-09-1990" Age = 29 RollNo = 16238627 Debug.Print Name, DoB, Age, RollNo End Sub
Step 9: To see the output, open the Immediate Window from the View menu list. Or we can use a short cut key as Ctrl + G to get this window.
Step 10: Run the code by pressing the F5 function key or click on the Play button located below the menu list.
We will see, all the variable which we have declared above, we are able to see the values stored in each of the variables.
Step 11: Now we will replace each variables String, Integer and Long with Variant data type as shown below.
Code:
Sub VBA_Variant1() Dim Name As Variant Dim DoB As Variant Dim Age As Variant Dim RollNo As Variant Name = "Ashwani" DoB = "02-09-1990" Age = 29 RollNo = 16238627 Debug.Print Name, DoB, Age, RollNo End Sub
Step 12: Again run the code. We will the same output as we got using different variable data type with the Variant data type.
And if we compare the output, then both outputs are the same.
Pros & Cons of Excel VBA Variant
- We can replace most of the data types with a single data type Variant.
- VBA Variant is easy as using Integer or Long or String data types for declaring variables.
- This saves time in thinking which type of data type we need to choose for variable declaration.
- For each different data, we will get the same output by using a Variant data type as we could get using traditional variables.
- We cannot use some certain types of variable data type such Double if we want to replace this with Variant.
Things to Remember
- Use double quote (Inverted commas) if you want to declare text using Variant or any other data types.
- We can choose any name to declare variable using Variant, as we used to perform with other types of data types.
- VBA Variant has the limitation where cannot use IntelliSense list, which has inbuilt functions.
- VBA always suggests the best possible data types we could declare of any type of data.
Recommended Articles
This is a guide to VBA Variant. Here we discuss how to declare Variant Data Type in Excel using VBA code along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA Workbook Open
- VBA Get Cell Value
- VBA Length of String
- VBA XML
Excel VBA Variant Data Type
Variant Data Type in VBA is a universal data type that can hold any data type, but while assigning the data type, we need to use the word “Variant.”
We all know how important variables are in VBA projects. Once the variable is declared, we need to assign a data type to the declared variables. Data type assignment in VBAData type is the core character of any variable, it represents what is the type of value we can store in the variable and what is the limit or the range of values which can be stored in the variable, data types are built-in VBA and user or developer needs to be aware which type of value can be stored in which data type. Data types assign to variables tells the compiler storage size of the variable.read more depends on what kind of data we need to assign to the declared variables.
Table of contents
- Excel VBA Variant Data Type
- How to Declare Variant Data Type?
- VBA Variant Doesn’t Require Explicit Way
- Things to Remember
- Recommended Articles
For example, look at the below code.
In the above code, we declare the variable as “IntegerNumber.“ We assigned the data type as “Integer.“
Before assigning the data type to the variable, we should be aware of the limitations of the variable. For example, since we have assigned the data type Integer, my variable can hold the numbers from -32768 to 32767.
Anything more than the data type limit will cause an error. So, if we want to store more than 32767 values, we need to assign the different data types which can hold more than 32767.
To overcome this limitation, we have a universal data type, “Variant.” This article will show you the complete guide on a Variant data type.
How to Declare Variant Data Type?
We can declare the variant data type as the usual data type, but while assigning the data type, we need to use the word “Variant.”
Code:
Sub Variant_Example1() Dim MyNumber As Variant End Sub
It makes the variable work any data now. We can assign any numbers, strings, dates, and many other things.
Below is the demonstration of the same.
Code:
Sub Variant_Example1() Dim MonthName As Variant Dim MyDate As Variant Dim MyNumber As Variant Dim MyName As Variant MonthName = "January" MyDate = "24-04-2019" MyNumber = 4563 MyName = "My Name is Excel VBA" End Sub
We have assigned a date, number, and string to the above variable. So, the Variant data type allows us not to worry about what kind of data we will store or assign.
As soon as we declare a variable as a “Variant.” While coding, we don’t have to worry about our data type somewhere in the middle of the project. It makes the variable work flexibly to our needs. We can probably carry out our operations in the project with a single variable.
VBA Variant Doesn’t Require Explicit Way
The general procedure to declare a VBA variable is first to name it and then assign the data type. Below is an example of the same.
It is the explicit way of declaring the variable. However, when we declare the Variant data type, we do not need to declare them explicitly. Rather, we can name the variable and leave out the data type part.
Code:
Sub Variant_Example1() Dim MyNumber End Sub
In the above code, we have named the variable “MyNumber,” but after naming it, we have not assigned any data type.
I have left out As [Data Type Name] part because the moment we ignore the data type assignment part, the variable becomes variant.
Things to Remember
Even though the “Variant” data type is flexible with the data, we will store it, but this is not the popular data type. Looks strange but is TRUE. People avoid using this data type unless there is any specific reason to use it. Below are some of the reasons for avoiding the use of variants.
- It ignores all the data mismatch errors.
- The variant data type limits us from accessing the IntelliSense list.
- VBA always guesses the best possible data type and assigns it accordingly.
- In the case of the Integer data type limit, the variant data type does not notify us when it crosses 32767 limits.
Recommended Articles
This article is a guide to VBA Variant. Here, we discuss how to declare and use the Variant data type, which is universal and holds any data type in VBA except fixed-length string data. You can learn more about VBA from the following articles: –
- VBA DoEvents
- Refresh Pivot Table using VBA Code
- Class Modules in VBA
- VBA Outlook
Тип Variant
Тип Variant обеспечивает «безразмерный» контейнер для хранения данных. Переменная этого типа может хранить данные любого из допустимых в VBA типов, включая числовые значения, строки, даты и объекты. Более того, одна и та же такая переменная в одной и той же программе в разные моменты может хранить данные различных типов. Например, следующий фрагмент программного кода вполне допустим (хотя вряд ли продуктивен):
Dim varЧтоУгодно As Variant
varЧтоУгодно = 3
varЧтоУгодно = «Я полагаю.»
varЧтоУгодно =#12/31/99 11:59:59 РМ#
VBA не только допускает такой набор операторов, но еще и помнит, данные какого типа вы помещаете в переменную типа Variant. Например, после выполнения последнего из приведенных выше операторов varЧтоУгодно будет идентифицироваться как переменная типа Variant/Date. Выяснить, данные какого типа хранятся в переменной типа Variant в данный момент, можно с помощью функции VBA TypeName. Например, если бы предыдущий фрагмент программного кода продолжался оператором
strVariantType = TypeName (varЧтоУгодно)
то значением переменной strVariantType было бы Date, поскольку данные именно такого типа находятся в varЧтоУгодно.
Благодаря такой своей гибкости переменные типа Variant очень удобны. Вместо того чтобы заботиться об использовании конкретных типов данных, можно всем переменным назначить тип Variant, и тогда в них легко помешать данные любых типов. Однако такой подход тоже имеет свои недостатки, о которых уже говорилось в разделе «Использование конкретного типа данных по сравнению с типом Variant: за и против».
Но даже если вы назначите конкретные типы данных всем своим переменным, переменные типа Variant не утратят своей роли хотя бы как черновые переменные для простых вычислений в небольших процедурах. А в VBA 5 и VBA 6 такие переменные придется использовать, если вам потребуется максимально допустимая в VBA точность вычислений (подробности — в следующем разделе).