Integer 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 this Article

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

Integer (Int) Variable Type

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

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

Dim intA as Integer

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

intA = 30000

Putting this in a procedure looks like this:

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

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

vba integer intexample msgbox

Long Variable Type

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

vba integer intexample overflow error

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

vba integer intexample overflow debug

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

Dim longA as Long

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

<<link to long variable article>>

Why would you use Int variables instead of Long variables?

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

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

Decimal Values & Int Data Types

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

Therefore, if you were to run the procedure below:

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

You would get the following result (rounding down):

vba integer passing decimal round down msgbox

However, this code below:

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

Would return the following message box (rounding up):

vba integer passing decimal round up msgbox

Decimal / Double Data Type

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

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

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

vba integer double example

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

Declare Int Variable at Module or Global Level

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

vba integer procedure declaration

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

Module Level

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

vba integer module declaration

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

VBA Coding Made Easy

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

automacro

Learn More

Global Level

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

Public IntA as Integer

vba integer global declaration

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

vba integer declaration notdefined

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

Convert String to Int

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

vba integer intexample string to integer immediate

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

Convert Int to String

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

vba integer intexample integer to string immediate

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

VBA Programming | Code Generator does work for you!

Format Integer Stored as String

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

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

Excel VBA Integer

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

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

What is the Integer Data Type?

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

VBA Integer

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

Examples of Excel VBA Integer Data Type

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

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

Example #1

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

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

Step 1: Declare the variable as Integer.

Code:

Sub Integer_Example()

  Dim k As Integer

End Sub

VBA Integer Example 1

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

Code:

Sub Integer_Example1()

  Dim k As Integer

  k = 500

End Sub

VBA Integer Example 1-1

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

Code:

Sub Integer_Example1()

  Dim k As Integer

  k = 500

  MsgBox k

End Sub

VBA Integer Example 1-2

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

VBA Integer Example 1-3

Example #2

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

Code:

Sub Integer_Example2()

  Dim k As Integer

  k = -500

  MsgBox k

End Sub

VBA Integer Example 2

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

VBA Integer Example 2-1

Example #3

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

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

Code:

Sub Integer_Example3()

    Dim k As Integer

    k = 85.456

    MsgBox k

End Sub

Example 3

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

VBA Integer Example 3-1

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

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

Code:

Sub Integer_Example3()

    Dim k As Integer

    k = 85.58

    MsgBox k

End Sub

Example 3-2

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

VBA Integer Example 3-3

Limitations of Integer Data Type in Excel VBA

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

For example, look at the below code.

Code:

Sub Integer_Example4()

    Dim k As Integer

    k = 40000

    MsgBox k

End Sub

Example 4

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

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

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

VBA Integer Example 4-1

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

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

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

Code:

Sub Integer_Example4()

    Dim k As Integer

    k = "Hello"

    MsgBox k

End Sub

Example 4-2

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

VBA Integer Example 4-3

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

Recommended Articles

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

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

Содержание

  1. Целочисленный тип данных (Visual Basic)
  2. Комментарии
  3. Литеральные назначения
  4. Советы по программированию
  5. Диапазон
  6. Сводка типов данных
  7. Набор встроенных типов данных
  8. Преобразование между типами данных
  9. Проверка типов данных
  10. Возвращаемые значения функции CStr
  11. См. также
  12. Поддержка и обратная связь
  13. Data type summary
  14. Set intrinsic data types
  15. Convert between data types
  16. Verify data types
  17. Return values for CStr
  18. See also
  19. Support and feedback

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

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

Комментарии

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Диапазон

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

Источник

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

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

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

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

Тип данных Размер хранилища Диапазон
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 и обратная связь.

Источник

Data type summary

A data type is the characteristic of a variable that determines what kind of data it can hold. Data types include those in the following table as well as user-defined types and specific types of objects.

Set intrinsic data types

The following table shows the supported data types, including storage sizes and ranges.

Data type Storage size Range
Boolean 2 bytes True or False
Byte 1 byte 0 to 255
Collection Unknown Unknown
Currency (scaled integer) 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807
Date 8 bytes January 1, 100, to December 31, 9999
Decimal 14 bytes +/-79,228,162,514,264,337,593,543,950,335 with no decimal point

+/-7.9228162514264337593543950335 with 28 places to the right of the decimal

Smallest non-zero number is+/-0.0000000000000000000000000001

Dictionary Unknown Unknown
Double (double-precision floating-point) 8 bytes -1.79769313486231E308 to -4.94065645841247E-324 for negative values

4.94065645841247E-324 to 1.79769313486232E308 for positive values

Integer 2 bytes -32,768 to 32,767
Long (Long integer) 4 bytes -2,147,483,648 to 2,147,483,647
LongLong (LongLong integer) 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Valid on 64-bit platforms only.

LongPtr (Long integer on 32-bit systems, LongLong integer on 64-bit systems) 4 bytes on 32-bit systems

8 bytes on 64-bit systems

-2,147,483,648 to 2,147,483,647 on 32-bit systems

-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 on 64-bit systems

Object 4 bytes Any Object reference
Single (single-precision floating-point) 4 bytes -3.402823E38 to -1.401298E-45 for negative values

1.401298E-45 to 3.402823E38 for positive values

String (variable-length) 10 bytes + string length 0 to approximately 2 billion
String (fixed-length) Length of string 1 to approximately 65,400
Variant (with numbers) 16 bytes Any numeric value up to the range of a Double
Variant (with characters) 22 bytes + string length (24 bytes on 64-bit systems) Same range as for variable-length String
User-defined (using Type) Number required by elements The range of each element is the same as the range of its data type.

A Variant containing an array requires 12 bytes more than the array alone.

Arrays of any data type require 20 bytes of memory plus 4 bytes for each array dimension plus the number of bytes occupied by the data itself. The memory occupied by the data can be calculated by multiplying the number of data elements by the size of each element.

For example, the data in a single-dimension array consisting of 4 Integer data elements of 2 bytes each occupies 8 bytes. The 8 bytes required for the data plus the 24 bytes of overhead brings the total memory requirement for the array to 32 bytes. On 64-bit platforms, SAFEARRAY’s take up 24-bits (plus 4 bytes per Dim statement). The pvData member is an 8-byte pointer and it must be aligned on 8 byte boundaries.

LongPtr is not a true data type because it transforms to a Long in 32-bit environments, or a LongLong in 64-bit environments. LongPtr should be used to represent pointer and handle values in Declare statements and enables writing portable code that can run in both 32-bit and 64-bit environments.

Use the StrConv function to convert one type of string data to another.

Convert between data types

See Type conversion functions for examples of how to use the following functions to coerce an expression to a specific data type: CBool, CByte, CCur, CDate, CDbl, CDec, CInt, CLng, CLngLng, CLngPtr, CSng, CStr, and CVar.

For the following, see the respective function pages: CVErr, Fix, and Int.

CLngLng is valid on 64-bit platforms only.

Verify data types

To verify data types, see the following functions:

Return values for CStr

If expression is CStr returns
Boolean A string containing True or False.
Date A string containing a date in the short date format of your system.
Empty A zero-length string («»).
Error A string containing the word Error followed by the error number.
Null A run-time error.
Other numeric A string containing the number.

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 Integer

Excel VBA Integer Data Type

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

How to Use VBA Integer Data Type in Excel?

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

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

VBA Integer – Example #1

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

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

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

VBA Integer Example 1-1

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

Code:

Sub VBAInteger1()

End Sub

VBA Integer Example 1-2

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

Code:

Sub VBAInteger1()

  Dim A

End Sub

VBA Integer Example 1-3

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

Code:

Sub VBAInteger1()

  Dim A As Integer

End Sub

VBA Integer Example 1-4

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

Code:

Sub VBAInteger1()

  Dim A As Integer

  A = 10

End Sub

VBA Integer Example 1-5

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

Code:

Sub VBAInteger1()

  Dim A As Integer

  A = 10

  MsgBox A

End Sub

VBA Integer Example 1-6

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

Result of Example 1-7

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

VBA Integer – Example #2

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

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

Code:

Sub VBAInteger2()

End Sub

VBA Integer Example 2-1

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

Code:

Sub VBAInteger2()

  Dim A

End Sub

VBA Integer Example 2-2

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

Code:

Sub VBAInteger2()

  Dim A As Integer

End Sub

VBA Integer Example 2-3

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

Code:

Sub VBAInteger2()

  Dim A As Integer

  A = -10

End Sub

VBA Integer Example 2-4

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

Code:

Sub VBAInteger2()

  Dim A As Integer

  A = -10

  MsgBox A

End Sub

VBA Integer Example 2-5

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

Result of Example 2-6

VBA Integer – Example #3

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

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

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

Code:

Sub VBAInteger3()

End Sub

VBA Integer Example 3-1

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

Code:

Sub VBAInteger3()

  Dim A

End Sub

VBA Integer Example 3-2

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

Code:

Sub VBAInteger3()

  Dim A As Integer

End Sub

VBA Integer Example 3-3

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

Code:

Sub VBAInteger3()

  Dim A As Integer

  A = 10.123

End Sub

VBA Integer Example 3-4

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

Code:

Sub VBAInteger3()

  Dim A As Integer

  A = 10.123

  MsgBox A

End Sub

VBA Integer Example 3-5

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

Result of Example 3-6

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

VBA Integer – Example #4

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

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

Code:

Sub VBAInteger4()

End Sub

VBA Integer Example 4-1

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

Code:

Sub VBAInteger4()

  Dim A As Integer

End Sub

VBA Integer Example 4-2

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

Code:

Sub VBAInteger4()

  Dim A As Integer

  A = 1012312

End Sub

VBA Integer Example 4-3

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

Code:

Sub VBAInteger4()

  Dim A As Integer

  A = 1012312

  MsgBox A

End Sub

VBA Integer Example 4-4

Step 5: Now compile and run the above code.

Result of Example 4-5

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

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

VBA Integer – Example #5

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

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

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

Code:

Sub VBAInteger5()

End Sub

Example 5-1

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

Code:

Sub VBAInteger5()

  Dim A As Integer

End Sub

Example 5-2

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

Code:

Sub VBAInteger5()

  Dim A As Integer

  A = "VBA Integer"

  MsgBox A

End Sub

Example 5-3

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

Result of Example 5-4

Pros of Excel VBA Integer

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

Things to Remember

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

Recommended Articles

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

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

Понравилась статья? Поделить с друзьями:
  • Integer to word conversion
  • Inspire definition of the word
  • Int to word java
  • Inspiration meaning of the word
  • Int to word codesys