Variant type in excel

VBA Variant Data Type in Excel explained with syntax and examples.Variant Data Type in Excel VBA explained with syntax and examples. It is a special and universal data type to use for any kind of data except fixed length string. It is more flexible, but occupies more space in memory. Type declaration character is not available for variant data type.

There are two types of variant data types..

1. Variant (numbers) and
2. Variant (characters)

Variant (numbers):

The Variant (numbers) can contain any numeric value as large as Double.The Variant numbers occupies 16 bytes (128 bits).

Variant (characters):

The Variant (characters) can contain Same as variant variable-length String. The Variant characters occupies 22 bytes (176 bits) and the memory that is required for the Variant itself.

Table of Contents:

  • Overview of Variant VBA Data Type in Excel
  • Data Type Variant Syntax in Excel VBA
  • Example on the Data Type Variant in Excel VBA
  • Convert an Expression to Variant VBA Data Type
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

Let us see Data Type Variant Syntax in Excel VBA.

Dim VariableName as Variant
'or
Dim VariableName

Where VariableName represents the name of the variable.
Variant represents type of data.

Example on the Variant in Excel VBA

Here is an example on the Variant numbers and characters in Excel VBA.

Sub VBAF1_Variant_DataType()
    
    'Variable declaration
    Dim Name As Variant
    Dim DateofJoin As Variant
    Dim Salary As Variant
    
    Name = "Patricia Katts"
    DateofJoin = #1/1/2019#
    Salary = 75000
    
End Sub

The above example accepted string, date and integer data types.

Convert an Expression to Variant Data Type in Excel VBA

You can convert an expression to Variant VBA data type using VBA CVar function. Click on the following link to learn about CVar function and complete tutorial and examples.

VBA CVar Function

Also read about all other data types.

VBA Data Types

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays VBA Text Files VBA Tables

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog

Содержание

  1. Тип данных Variant
  2. См. также
  3. Поддержка и обратная связь
  4. Сводка типов данных
  5. Набор встроенных типов данных
  6. Преобразование между типами данных
  7. Проверка типов данных
  8. Возвращаемые значения функции CStr
  9. См. также
  10. Поддержка и обратная связь
  11. Understanding Variants
  12. См. также
  13. Поддержка и обратная связь
  14. Variant data type
  15. See also
  16. Support and feedback

Тип данных Variant

Тип данных Variant является типом данных для всех переменных, для которых в явной форме не объявлен другой тип (с использованием таких операторов, как Dim, Private, Public или Static).

Типы данных Variant не имеют символа объявления типа .

Variant — это специальный тип данных, который может содержать любой вид данных, кроме данных с фиксированной длиной String. (Типы Variant теперь поддерживают пользовательские типы). Тип Variant также может содержать специальные значения Empty, Error, Nothing и Null. Вы можете определить, как данные типа Variant обрабатываются с использованием функции VarType или TypeName.

Используйте функцию VarType чтобы проверить, какой тип данных содержится в Variant.

Числовые данные могут быть любым целым или действительным числом из диапазона от -1,797693134862315E308 до -4,94066E-324 для отрицательных значений и от 4,94066E-324 до 1,797693134862315E308 для положительных значений.

Обычно числовые данные Variant хранятся в Variant в исходном виде. Например, если назначить Integer типу Variant, последующая операция обрабатывает тип Variant как Integer. Однако в том случае, когда с типом Variant, содержащим Byte, Integer, Long или Single, выполняется арифметическая операция и результат выходит за пределы обычного диапазона для исходного типа данных, этот результат повышается в рамках Variant до следующего по величине типа данных. Byte повышается до Integer, Integer повышается до Long, а Long и Single повышаются до Double.

Если переменные Variant, содержащие значения Currency, Decimal и Double, выходят за границы соответствующего диапазона, возникает ошибка.

Используйте тип данных Variant вместо любого другого типа данных, чтобы сделать работу с данными более гибкой. Если переменная Variant содержит цифры, в зависимости от контекста они могут быть как строковым представлением этих цифр, так и их фактическим значением. Пример:

В предыдущем примере MyVar содержит числовое представление — фактическое значение 98052 . Арифметические операторы работают ожидаемым образом для переменных Variant, содержащих числовые значения или строковые данные, которые можно интерпретировать как числа. Если вы используете оператор + для сложения MyVar с другой переменной Variant, содержащей число, или с переменной числового типа, результатом является арифметическая сумма.

Значение Empty указывает переменную Variant, которая еще не была инициализирована (ей не было назначено начальное значение). Переменная Variant со значением Empty равна 0 при использовании в числовом контексте и строке нулевой длины («») при использовании в строковом контексте.

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

Error в Variant представляет собой специальное значение, используемое для указания на возникновение в процедуре состояния ошибки. Однако в отличие от других типов ошибок обычная обработка ошибки на уровне приложений не выполняется. Это позволяет как вам, так и приложению предпринять некоторые альтернативные действия на основании значения ошибки. Значения Error создаются посредством преобразования действительных чисел в значения ошибки с помощью функции CVErr.

См. также

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

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

Источник

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

См. также

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

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

Источник

Understanding Variants

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

Переменные, объявленные как тип данных Variant , могут содержать значения string, date, time, boolean или numeric и могут автоматически преобразовывать содержащиеся в них значения. Для числовых значений Variant требуется 16 байт памяти (что важно только для больших процедур или сложных модулей), и доступ к им медленнее, чем явно типизированные переменные любого другого типа. Вы редко используете тип данных Variant для константы. Строковые значения типа Variant требуют 22 байта памяти.

Следующие операторы создают переменные Variant:

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

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

См. также

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

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

Источник

Variant data type

The Variant data type is the data type for all variables that are not explicitly declared as some other type (using statements such as Dim, Private, Public, or Static).

The Variant data type has no type-declaration character.

A Variant is a special data type that can contain any kind of data except fixed-length String data. (Variant types now support user-defined types.) A Variant can also contain the special values Empty, Error, Nothing, and Null. You can determine how the data in a Variant is treated by using the VarType function or TypeName function.

Use the VarType function to test what type of data is held in a Variant.

Numeric data can be any integer or real number value ranging from -1.797693134862315E308 to -4.94066E-324 for negative values and from 4.94066E-324 to 1.797693134862315E308 for positive values.

Generally, numeric Variant data is maintained in its original data type within the Variant. For example, if you assign an Integer to a Variant, subsequent operations treat the Variant as an Integer. However, if an arithmetic operation is performed on a Variant containing a Byte, an Integer, a Long, or a Single, and the result exceeds the normal range for the original data type, the result is promoted within the Variant to the next larger data type. A Byte is promoted to an Integer, an Integer is promoted to a Long, and a Long and a Single are promoted to a Double.

An error occurs when Variant variables containing Currency, Decimal, and Double values exceed their respective ranges.

Use the Variant data type in place of any data type to work with data in a more flexible way. If the contents of a Variant variable are digits, they may be either the string representation of the digits or their actual value, depending on the context. For example:

In the preceding example, MyVar contains a numeric representation—the actual value 98052 . Arithmetic operators work as expected on Variant variables that contain numeric values or string data that can be interpreted as numbers. If you use the + operator to add MyVar to another Variant containing a number or to a variable of a numeric type, the result is an arithmetic sum.

The value Empty denotes a Variant variable that hasn’t been initialized (assigned an initial value). A Variant containing Empty is 0 if it is used in a numeric context, and a zero-length string («») if it is used in a string context.

Don’t confuse Empty with Null. Null indicates that the Variant variable intentionally contains no valid data.

In a Variant, Error is a special value used to indicate that an error condition has occurred in a procedure. However, unlike for other kinds of errors, normal application-level error handling does not occur. This allows you, or the application itself, to take some alternative action based on the error value. Error values are created by converting real numbers to error values by using the CVErr function.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

VBA Variant

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.

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.

Variant Data Type

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.

VBA Variant Example 1-1

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

VBA Variant Example 1-2

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

VBA Variant Example 1-3

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

VBA Variant Example 1-4

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

Datatype Integer Example 1-5

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

Datatype Long Example 1-6

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

VBA Variant Example 1-7

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

Use Debug Print function

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.

Immediate Window Example 1-9

Step 10: Run the code by pressing the F5 function key or click on the Play button located below the menu list.

VBA Variant Example 1-10

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

VBA Variant Example 1-9

Step 12: Again run the code. We will the same output as we got using different variable data type with the Variant data type.

VBA Variant Example 1-11

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 –

  1. VBA Workbook Open
  2. VBA Get Cell Value
  3. VBA Length of String
  4. VBA XML

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


Previously. we learned about various numerical and nonnumerical data types in the VBA programming language. Today, we would learn about another particular data type which is known as a variant. Variants are easy to use and provide additional functionality to our code.

So let us start learning about variants in the VBA Programming language.

Table of Contents

  1. What are Variants in VBA?
  2. Declaring a Variant in VBA
    1. The syntax for Explicit Declaration of Variant
    2. The syntax for Implicit Declaration of a Variant
  3. Example to Use Variant in VBA
  4. Module Level Variant
  5. Global Level Variant

What are Variants in VBA?

A Variant is a special type of variable having any data type including Integers, strings, decimals, or even objects. When we do not specify the data type of a variable then it becomes a variant and its data type would be automatically decided on the basis of the value assigned to the variant.

Generally, we avoid using variants in VBA code because they require extra main memory.

You can download the practice workbook to follow along this article.

Declaring a Variant in VBA

There are two ways to declare a variant type variable in VBA Programming language, Explicit Declaration, and Implicit Declaration.

The syntax for Explicit Declaration of Variant

In this method, we explicitly tell the data type of variable to be a variant at the time of its declaration.

Dim <variant_name> As Variant

For example, we have these examples of explicit variant declarations.

Dim var1 As Variant
Dim var2 As Variant

The syntax for Implicit Declaration of a Variant

We can implicitly declare a variant if we do not specify the data type of a variable when declaring it, it is automatically declared as a variant. We remove the As <Data_Type> part of the normal variable declaration then it becomes an implicit variant declaration.

Dim <Variant_Name>

For instance, we are having examples of some valid implicit variant declarations in VBA.

Sub Implicit_Declaration()
Dim Name
Dim Roll
Dim group
Dim percentage

Name="Chetna Dua"          'name variant becomes text string
Roll=45                    'roll becomes an integer 
group="BCA Final year"     'group is assigned to a text string
percentage=45.53           'data type of percentage changes to double

Debug.Print Name,Roll,group,percentage

End Sub
implicit variant declaration in vba

infographics variant data type in vba

Example to Use Variant in VBA

Within the program, if we reassign the value then the variant can change its data type based on the type of the newly assigned value.

For instance, look at this code.

Sub example()
Dim var                            'no data type specified by the user
var = "ExcelUnlocked"              'string literal assigned 
Debug.Print var;
var = 56                           'integral literal assigned
Debug.Print var
End Sub
  • We have declared a variable named var using the Dim keyword but we didn’t specify its data type.
  • We assigned the string literal “ExcelUnlocked” to var. Now var has a String data type.
  • When we reassign the var with a string literal 56, var changes its data type to Integer and stores 56 in it.

When we run the above Sub Procedure, we get the value of the variable on the Immediate Window in VBE Interface.

Press Ctrl and G keys together to open the Immediate Window in Visual Basic Editor. This window prints the messages with the help of Debug.Print method

how to use variant in vba

Module Level Variant

The Variant declared in the above examples are local to the Sub Procedure in which they are declared. We cannot access the value of the variant out of the Sub Procedure block in which we declare it.

Module Level variant can be accessed or updated in any sub-procedure of the module. To declare a variant at a module level, use the declaration statement out of all the Sub Procedures at the top of the VBA Module code.

module level variant in vba

Global Level Variant

A Global level variant can be accessed or updated from all the Sub Procedures of all the modules of our VBA Project. We use the Public keyword to declare a Globar level variant at the top of the VBA Module code.

Public <Variant_name> As Variant

This brings us to an end.

Thank you for reading.

RELATED POSTS

  • User Defined Data Type – Type VBA

  • Constants in VBA – Declaration, Types. Scope

  • Strings in VBA – Fixed and Variable Length

  • When to Use Static Variables in VBA?

  • For Each Loop VBA – Excel

  • Optional Arguments in VBA – Usage with Examples

Понравилась статья? Поделить с друзьями:
  • Variant array in excel vba
  • Variant 1 choose the right word
  • Variance function in excel
  • Variance formula in excel
  • Variable field in word