Vba dim excel описание

На чтение 25 мин. Просмотров 12.3k.

VBA Dim

Алан Перлис

Постоянная одного человека — переменная другого

Эта статья содержит полное руководство по работе с переменными и использованию VBA Dim.

Первый раздел содержит краткое руководство по использованию оператора
Dim, включая примеры и формат оператора Dim.

Остальная часть поста содержит наиболее полное руководство, которое вы
найдете в VBA Dim Statement.

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

Содержание

  1. Краткое руководство по использованию VBA Dim Statement
  2. Полезные ссылки 
  3. Что такое VBA Dim Statement?
  4. Формат VBA Dim Statement
  5. Как использовать Dim с несколькими переменными
  6. Где я должен поместить Dim Statement?
  7. Использование Dim в циклах
  8. Могу ли я использовать Dim для присвоения значения?
  9. Dim действительно требуется?
  10. Использование Dim с Basic Variables
  11. Использование Dim с Variants
  12. Использование Dim с Objects
  13. Использование Dim с Arrays
  14. Устранение неполадок ошибок  Dim
  15. Локальные и глобальные переменные
  16. Заключение

Краткое руководство по использованию VBA Dim Statement

Описание Формат Пример
Базовая
переменная
Dim [имя
переменной] 
As [Тип]
Dim count As Long
Dim amount 
As Currency
Dim name As String
Dim visible 
As Boolean
Фиксированная
строка
Dim [имя
переменной] 
As String *[размер]
Dim s As String * 4
Dim t As String * 10
Вариант Dim [имя
переменной] 
As Variant
Dim [имя
переменной]
Dim var As Variant
Dim var
Объект
использует
Dim и New
Dim [имя
переменной] 
As New [тип объекта]
Dim coll As New 
Collection
Dim coll As New 
Class1
Объект
использует
Dim и New
Dim [имя
переменной] 
As [тип объекта]
Set [имя
переменной] = New [тип объекта]
Dim coll As Collection
Set coll = New 
Collection
Dim coll As Class1
Set coll = New Class1
Статический
массив
Dim [имя
переменной]
([первый] 
To [последний] ) 
As[Тип]
Dim arr(1 To 6) 
As Long
Динамический
массив
Dim [имя
переменной]() 
As [Тип]
ReDim [имя
переменной]
([первый] 
To [последний])
Dim arr() As Long
ReDim arr(1 To 6)
Внешняя
библиотека
(Раннее
связывание) *
Dim [имя
переменной] 
As New [пункт]
Dim dict 
As New Dictionary
Внешняя
библиотека
(Раннее
связывание с
использованием
Set) *
Dim [имя
переменной] 
As [пункт]
Set [имя
переменной] = 
New [пункт]
Dim dict As Dictionary
Set dict = 
New Dictonary 
Внешняя
библиотека
(Позднее
связывание)
Dim [имя
переменной] 
As Object
Set [имя
переменной] = CreateObject
(«[библиотека]»)
Dim dict As Object
Set dict = CreateObject(«Scripting.
Dictionary»)

* Примечание. Для раннего связывания необходимо добавить
справочный файл с помощью меню «Инструменты» -> «Ссылки». Смотрите здесь,
как добавить ссылку на Dictonary.

Полезные ссылки 

  • Объявление параметров в подпрограмме или функции
  • Использование объектов в VBA
  • Массивы VBA
  • Коллекции VBA
  • Словарь VBA
  • VBA Workbook
  • VBA Worksheet

Что такое VBA Dim Statement?

Ключевое слово Dim — это сокращение от Dimension. Он
используется для объявления переменных в VBA.

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

Существует четыре типа Dim Statement. Все они очень похожи по синтаксису.

Вот они:

  1. Basic variable
  2. Variant
  3. Object
  4. Array

Ниже приводится краткое описание каждого типа

  1. Basic variable — этот тип переменной содержит одно значение. Это такие типы, как Long, String, Date, Double, Currency.
  2. Variant — VBA решает во время выполнения, какой тип будет использоваться. Вы должны избегать вариантов, где это возможно, но в некоторых случаях требуется их использование.
  3. Object — это переменная, которая может иметь несколько методов (то есть подпрограмм / функций) и несколько свойств (то есть значений). Есть 3 вида:
    Объекты Excel, такие как объекты Workbook, Worksheet и Range.
    Пользовательские объекты, созданные с использованием модулей классов.
    Внешние библиотеки, такие как Словарь.
  4. Array — это группа переменных или объектов.

В следующем разделе мы рассмотрим формат оператора VBA Dim с
некоторыми примерами каждого из них.

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

Формат VBA Dim Statement

Формат выражения Dim показан ниже.

' 1. BASIC VARIABLE
' Объявление основной переменной
Dim [Имя переменной] As [тип]

' Объявление фиксированной строки
Dim [Имя переменной] As String * [размер]

' 2. VARIANT
Dim [Имя переменной] As Variant
Dim [Имя переменной]

' 3. OBJECT
' Объявление объекта
Dim [Имя переменной] As [тип]

' Объявление и создание объекта
Dim [Имя переменной] As New [тип]

' Объявление объекта с использованием позднего связывания
Dim [Имя переменной] As Object

' 4. ARRAY
' Объявление статического массива
Dim [Имя переменной](first To last) As [тип]

' Объявление динамического массива
Dim [Имя переменной]() As [тип]
Ниже приведены примеры использования различных форматов.
Sub Primeri()

    ' 1. BASIC VARIABLE
    ' Объявление основной переменной
    Dim name As String
    Dim count As Long
    Dim amount As Currency
    Dim eventdate As Date
    
    ' Объявление фиксированной строки
    Dim userid As String * 8
    
    ' 2. VARIANT
    Dim var As Variant
    Dim var
    
    ' 3. OBJECT
    ' Объявление объекта
    Dim sh As Worksheet
    Dim wk As Workbook
    Dim rg As Range
    
    ' Объявление и создание объекта
    Dim coll1 As New Collection
    Dim o1 As New Class1
    
    ' Объявление объекта - создайте объект ниже, используя Set
    Dim coll2 As Collection
    Dim o2 As Class1
    
    Set coll2 = New Collection
    Set o2 = New Class1
    
    ' 	Объявление и присвоение с использованием позднего связывания
    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    
    ' 4. ARRAY
    ' Объявление статического массива
    Dim arrScores(1 To 5) As Long
    Dim arrCountries(0 To 9) As String
    
    ' Объявление динамического массива - установите размер ниже, используя ReDim
    Dim arrMarks() As Long
    Dim arrNames() As String
    
    ReDim arrMarks(1 To 10) As Long
    ReDim arrNames(1 To 10) As String

End Sub

Мы рассмотрим эти различные типы операторов Dim в следующих
разделах.

Как использовать Dim с несколькими переменными

Мы можем объявить несколько переменных в одном выражении Dim.

Dim name As String, age As Long, count As Long

Если мы опускаем тип, то VBA автоматически устанавливает тип как Variant. Мы увидим больше
о Variant позже.

' Сумма является вариантом
Dim amount As Variant

' Сумма является вариантом
Dim amount

' Адрес это вариант - имя это строка
Dim name As String, address

' имя - это вариант, адрес – строка
Dim name, address As String

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

Dim wk As Workbook, marks As Count, name As String

Вы можете поместить столько переменных, сколько захотите, в
одном выражении Dim, но
для удобства чтения рекомендуется оставить его равным 3 или 4.

Где я должен поместить Dim Statement?

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

Если переменная используется перед оператором Dim, вы получите ошибку
«переменная не определена»

Dim statements

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

Sub DimVverh()

    ' Размещение всех Dim statements наверху
    Dim count As Long, name As String, i As Long
    Dim wk As Workbook, sh As Worksheet, rg As Range
    
    Set wk = Workbooks.Open("C:ДокументыОтчет.xlsx")
    Set sh = wk.Worksheets(1)
    Set rg = sh.Range("A1:A10")
    
    For i = 1 To rg.Rows.count
        count = rg.Value
        Debug.Print count
    Next i
  
End Sub

ИЛИ вы можете объявить переменные непосредственно перед их
использованием:

Sub DimIsp()

    Dim wk As Workbook
    Set wk = Workbooks.Open("C:ДокументыОтчет.xlsx")
    
    Dim sh As Worksheet
    Set sh = wk.Worksheets(1)
    
    Dim rg As Range
    Set rg = sh.Range("A1:A10")
    
    Dim i As Long, count As Long, name As String
    For i = 1 To rg.Rows.count
        count = rg.Value
        name = rg.Offset(0, 1).Value
        Debug.Print name, count
    Next i
  
End Sub

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

Использование Dim в циклах

Помещение оператора Dim в цикл не влияет на переменную.

Когда VBA запускает Sub (или Function), первым делом он
создает все переменные, которые были объявлены в выражениях Dim.

Следующие 2 фрагмента кода практически одинаковы. Во-первых,
переменная Count объявляется перед циклом. Во втором он объявлен в цикле.

Sub CountPeredCiklom()

    Dim count As Long

    Dim i As Long
    For i = 1 To 3
        count = count + 1
    Next i
    
    ' значение счета будет 3
    Debug.Print count

End Sub
Sub CountPosleCikla()

    Dim i As Long
    For i = 1 To 3
        Dim count As Long
        count = count + 1
    Next i
    
    ' значение счета будет 3
    Debug.Print count

End Sub

Код будет вести себя точно так же, потому что VBA создаст переменные при
входе в подпрограмму.

Могу ли я использовать Dim для присвоения значения?

В таких языках, как C ++, C # и Java, мы можем объявлять и назначать переменные в одной строке:

' C++
int i = 6
String name = "Иван"

Мы не можем сделать это в VBA. Мы можем использовать оператор двоеточия для размещения
объявлений и назначения строк в одной строке.

Dim count As Long: count = 6

Мы не объявляем и не присваиваем в одной строке VBA. Что мы
делаем, это помещаем эти две строки (ниже) в одну строку в редакторе. Что
касается VBA, это две отдельные строки, как здесь:

Dim count As Long
count = 6

Здесь мы помещаем 3 строки кода в одну строку редактора,
используя двоеточие:

count = 1: count = 2: Set wk = ThisWorkbook

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

Dim действительно требуется?

Ответ в том, что это не обязательно. VBA не требует от вас
использовать Dim Statement.

Однако не использовать оператор Dim — плохая практика и
может привести к множеству проблем.

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

Это может привести к таким проблемам, как

  1. Все переменные являются вариантами (проблемы с
    этим см. В разделе «Варианты»).
  2. Некоторые переменные ошибки останутся
    незамеченными.

Из-за этих проблем рекомендуется сделать использование Dim
обязательным в нашем коде. Мы делаем это с помощью оператора Option Explicit.

Option Explicit

 Мы можем сделать Dim
обязательным в модуле, набрав «Option Explicit» в верхней части модуля.

Мы можем сделать это автоматически в каждом новом модуле,
выбрав Tools-> Options из меню и отметив флажок «Требовать декларацию
переменной». Затем, когда вы вставите новый модуль, «Option Explicit» будет
автоматически добавлен в начало.

VBA Require Variable Declaration

Давайте посмотрим на некоторые ошибки, которые могут
остаться незамеченными, если мы не будем использовать Dim.

Ошибки Переменной

В приведенном ниже коде мы используем переменную Total без использования оператора Dim.

Sub BezDim()

    Total = 6
    
    Total = Total + 1
    
    Debug.Print Total

End Sub

Если мы случайно написали Total неправильно, VBA сочтет это
новой переменной.

В приведенном ниже коде мы неправильно написали переменную Total как Totall.

Sub BezDimOshibki()

    Total = 6
    
    ' Первый Total - это ошибка
    Totall = Total + 1
    
    ' напечатает 6 вместо 7
    Debug.Print Total

End Sub

VBA не обнаружит ошибок в коде, и будет напечатано неверное
значение.

Давайте добавим Option Explicit и попробуйте приведенный
выше код снова

Option Explicit 

Sub BezDimOshibki()

    Total = 6
    
    ' Первый Total - это ошибка
    Totall = Total + 1
    
    ' Напечатает 6 вместо 7
    Debug.Print Total

End Sub

Теперь, когда мы запустим код, мы получим ошибку «Переменная
не определена». Чтобы эта ошибка не появлялась, мы должны использовать Dim для каждой переменной,
которую мы хотим использовать.

Когда мы добавим оператор Dim для Total
и запустим код, мы получим ошибку, сообщающую, что опечатка Totall не была определена.

variable not defined 2

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

Ошибка в ключевом слове

Вот второй пример, который более тонкий.

Когда следующий код выполняется, он должен изменить шрифт в
ячейке A1 на синий.

Однако, когда код запускается, ничего не происходит.

Sub ZadatCvet()

    Sheet1.Range("A1").Font.Color = rgblue

End Sub

Ошибка здесь в том, что rgblue должен быть rgbBlue. Если вы
добавите Option Explicit в модуль, появится ошибка «переменная не определена».
Это значительно облегчает решение проблемы.

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

Использование Dim с Basic Variables

VBA имеет те же основные типы переменных, которые
используются в электронной таблице Excel.

Вы можете увидеть список всех типов переменных VBA здесь.

Тем не менее, большую часть времени вы будете использовать следующие:

Тип Хранение Диапазон Описание
Boolean 2 байта ИСТИНА или ЛОЖЬ Эта переменная
может быть
ИСТИНА или
ЛОЖЬ.
Long 4 байта от -2,147,483,648
до 2,147,483,647
Long — это
сокращение от
Long Integer.
Используйте это
вместо
типа Integer *
Currency 8 байт от -1,79769313486231E308
до -4,94065645841247E-324
для отрицательных
значений;
от 4.94065645841247E-324
до 1.79769313486232E308
для положительных
значений
Аналогично
Double,
но имеет
только 4
знака после
запятой
Double 8 байт от -922,337,203,685,477.5808
до 922,337,203,685,477.5807
Date 8 байт С 1 января 100
по 31 декабря 9999
String меняется От 0 до примерно
2 миллиардов
Содержит
текст

* Первоначально мы использовали бы тип Long вместо Integer,
потому что Integer был 16-разрядным, и поэтому диапазон был от -32 768 до 32
767, что довольно мало для многих случаев использования целых чисел.

Однако в 32-битной (или выше) системе целое число автоматически
преобразуется в длинное. Поскольку Windows была 32-битной начиная с Windows 95
NT, нет смысла использовать Integer.

В двух словах, всегда используйте Long для целочисленного
типа в VBA.

Фиксированный тип строки

В VBA есть один необычный тип базовой переменной, с которым
вы, возможно, не знакомы.

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

Sub TipStroki()

    Dim s As String
    
    ' s is "Иван Петров"
    s = "John Smith"
    
    ' s is "Игорь"
    s = "Tom"

End Sub

Фиксированная строка никогда не изменяется. Эта строка
всегда будет иметь одинаковый размер независимо от того, что вы ей назначаете

вот несколько примеров:

Sub FiksStroka()
    
    Dim s As String * 4
    
    ' s is "Иван"
    s = "Иван Перов"
    
    ' s = "Игорь "
    s = "Игорь"

End Sub

Использование Dim с Variants

Когда мы объявляем переменную как вариант, VBA решает во время выполнения, какой
тип переменной должен быть.

Мы объявляем варианты следующим образом

' Оба варианта
Dim count
Dim count As Variant
Это звучит как отличная идея в теории. Больше не нужно беспокоиться о типе переменной
Sub IspVariants()
    
    Dim count As Variant
        
    count = 7
    
    count = "Иван"
    
    count = #12/1/2018#

End Sub

Однако использование вариантов является плохой практикой, и
вот почему:

  1. VBA
    не будет замечать неправильных ошибок типа (т. Е. Несоответствие данных).
  2. Вы не можете получить доступ к Intellisense.
  3. VBA
    угадывает лучший тип, и это может быть не то, что вы хотите.

Тип ошибки

Ошибки твои друзья!

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

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

Например. Представьте, что у нас есть лист оценок учеников.
Если кто-то случайно (или намеренно) заменит метку на текст, данные будут
недействительными.

Если мы используем вариант для хранения меток, то ошибки не
возникнет

Sub MarksVariant()
    
    Dim marks As Variant
    
    Dim i As Long
    For i = 1 To 10
        
        ' Прочитайте отметку
        mark = Sheet1.Range("A" & i).Value
        
    Next

End Sub

Это не хорошо, потому что в ваших данных есть ошибка, а вы
не знаете об этом.

Если вы зададите переменную Long, VBA сообщит вам об ошибке
«Несоответствие типов», если значения являются текстовыми.

Sub MarksLong()
    
    Dim mark As Long
    
    Dim i As Long
    For i = 1 To 10
        
        ' Прочитайте отметку
        mark = Sheet1.Range("A" & i).Value
        
    Next

End Sub

Доступ к Intellisense

Intellisense — удивительная особенность VBA. Он дает вам
доступные параметры в зависимости от типа, который вы создали.

Представьте, что вы объявляете переменную листа, используя
Dim

Когда вы используете переменную wk с десятичной точкой, VBA
автоматически отобразит доступные опции для переменной.

Вы можете увидеть Intellisense на скриншоте ниже

VBA Intellisense

Если вы используете Variant как тип, то Intellisense будет
недоступен

Это потому, что VBA не будет знать тип переменной до времени
выполнения.

Использование Dim с Objects

Если вы не знаете, что такое Objects, вы можете прочитать
мою статью об VBA Objects здесь.

Есть 3 типа объектов:

  1. Объекты Excel
  2. Объекты модуля класса
  3. Внешние объекты библиотеки

Примечание. Объект VBA Collection используется аналогично тому, как мы используем объект Class Module. Мы используем новое, чтобы создать его.

Давайте посмотрим на каждый из них по очереди.

Объекты Excel

Объекты Excel, такие как Рабочая книга, Рабочий лист,
Диапазон и т. Д., Не используют Новый, поскольку они автоматически создаются
Excel. Смотрите, «когда New не требуется».

При создании или открытии книги Excel автоматически создает
связанный объект.

Например, в приведенном ниже коде мы открываем рабочую
книгу. VBA создаст объект, а функция Open вернет книгу, которую мы можем
сохранить в переменной

Sub OtkrWorkbook()
    
    Dim wk As Workbook
    Set wk = Workbooks.Open("C:ДокументыОтчет.xlsx")

End Sub

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

Sub DobavSheet()
    
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Worksheets.Add

End Sub

Нам не нужно использовать ключевое слово New для этих объектов Excel.

Мы просто присваиваем переменную функции, которая либо
создает новый объект, либо дает нам доступ к существующему.

Вот несколько примеров назначения переменных Workbook, Worksheet и range

Sub DimWorkbook()
    
    Dim wk As Workbook
    
    ' назначить wk новой книге
    Set wk = Workbooks.Add
    
    ' назначить wk первой открытой книге
    Set wk = Workbooks(1)
    
    ' назначить wk рабочей книге Отчет.xlsx
    Set wk = Workbooks("Отчет.xlsx")
    
    ' назначить wk активной книге
    Set wk = ActiveWorkbook
    
End Sub
Sub DimWorksheet()
    
    Dim sh As Worksheet
    
    ' Назначить sh на новый лист
    Set sh = ThisWorkbook.Worksheets.Add
    
    ' Назначьте sh на крайний левый лист
    Set sh = ThisWorkbook.Worksheets(1)
    
    ' Назначьте sh на лист под названием «Клиенты»
    Set sh = ThisWorkbook.Worksheets("Клиенты")
    
    ' Присвойте sh активному листу
    Set sh = ActiveSheet

End Sub
Sub DimRange()

    ' Получить рабочий лист клиента
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Worksheets("Клиенты")
    
    ' Объявите переменную диапазона
    Dim rg As Range
    
    ' Присвойте rg диапазону A1
    Set rg = sh.Range("A1")
    
    ' Назначьте rg в диапазоне от B4 до F10
    Set rg = sh.Range("B4:F10")
    
    ' Присвойте rg диапазону E1
    Set rg = sh.Cells(1, 5)
    
End Sub

Если вы хотите узнать больше об этих объектах, вы можете ознакомиться со следующими статьями: Workbook VBA, Worksheet VBA и Cell и Range VBA.

Использование Dim с Class Module Objects

В VBA мы используем Class Modules для создания наших собственных пользовательских объектов. Вы можете прочитать все о Class Modules здесь.

Если мы
создаем объект, нам нужно использовать ключевое слово New.

Мы можем сделать это в операторе Dim или в операторе Set.

Следующий код создает объект, используя ключевое слово New в выражении Dim:

' Объявить и создать
Dim o As New class1
Dim coll As New Collection

Использование New в выражении Dim означает, что каждый раз
при запуске нашего кода будет создаваться ровно один объект.

Использование Set дает нам больше гибкости. Мы можем создать
много объектов из одной переменной. Мы также можем создать объект на основе
условия.

Этот следующий код показывает, как мы создаем объект Class Module, используя Set. (Чтобы создать модуль класса, перейдите в окно проекта, щелкните правой кнопкой мыши соответствующую книгу и выберите «Вставить модуль класса». Подробнее см. «Создание Simple Class Module».)

' Объявить только
Dim o As Class1

' Создать с помощью Set
Set o = New Class1

Давайте посмотрим на пример использования Set. В приведенном ниже коде мы хотим
прочитать диапазон данных. Мы создаем объект только в том случае, если значение
больше 50.

Мы используем Set для создания объекта Class1. Это потому, что количество нужных нам объектов зависит от
количества значений более 50.

Sub IspSet()
    
    ' Объявите переменную объекта Class1
    Dim o As Class1
    
    ' Читать диапазон
    Dim i As Long
    For i = 1 To 10
        If Sheet1.Range("A" & i).Value > 50 Then

            ' Создать объект, если условие выполнено
            Set o = New Class1
            
        End If
    Next i

End Sub

Я сохранил этот пример простым для ясности. В реальной версии этого кода мы бы заполнили объект Class Module данными и добавили его в структуру данных, такую как Collection или Dictionary.

Вот пример реальной версии, основанной на данных ниже:

dim sample data

' Class Module - clsStudent
Public Name As String
Public Subject As String

' Стандартный модуль
Sub ChitatBalli()

    ' Создать коллекцию для хранения объектов
    Dim coll As New Collection
    
    ' Current Region получает соседние данные
    Dim rg As Range
    Set rg = Sheet1.Range("A1").CurrentRegion
    
    Dim i As Long, oStudent As clsStudent
    For i = 2 To rg.Rows.Count
        
        ' Проверьте значение
        If rg.Cells(i, 1).Value > 50 Then
            ' Создать новый объект
            Set oStudent = New clsStudent
            
            ' Читать данные на объект студента
            oStudent.Name = rg.Cells(i, 2).Value
            oStudent.Subject = rg.Cells(i, 3).Value
            
            ' добавить объект в коллекцию
            coll.Add oStudent
            
        End If
        
    Next i
    
    ' Распечатайте данные в Immediate Window, чтобы проверить их
    Dim oData As clsStudent
    For Each oData In coll
        Debug.Print oData.Name & " studies " & oData.Subject
    Next oData

End Sub

Чтобы узнать больше о Set вы можете заглянуть сюда.

Объекты из внешней библиотеки

Действительно полезная часть VBA — это то, как у нас есть
доступ к внешним библиотекам. Это открывает целый новый мир тому, что мы можем
сделать.

Примерами являются библиотеки Access, Outlook и Word,
которые позволяют нам взаимодействовать с этими приложениями.

Мы можем использовать библиотеки для различных типов
структур данных, таких как Словарь, Массив, Стек и Очередь.

Существуют библиотеки для очистки веб-сайта (библиотека
объектов Microsoft HTML), использования регулярных выражений (регулярные
выражения Microsoft VBScript) и многих других задач.

Мы можем создать эти объекты двумя способами:

  1. Раннее связывание
  2. Позднее связывание

Давайте посмотрим на это по очереди.

Раннее связывание

Раннее связывание означает, что мы добавляем справочный
файл. Как только этот файл добавлен, мы можем рассматривать объект как объект
модуля класса.

Мы добавляем ссылку, используя Tools-> Reference, а затем
проверяем соответствующий файл в списке.

Например, чтобы использовать словарь, мы ставим флажок
«Microsoft Scripting Runtime»

vba references dialog

Как только мы добавим ссылку, мы можем использовать словарь
как объект модуля класса

Sub RanSvyaz()

    ' Используйте только Dim
    Dim dict1 As New Dictionary
    
    ' Используйте Dim и Set
    Dim dict2 As Dictionary
    Set dict2 = New Dictionary

End Sub

Преимущество раннего связывания заключается в том, что у нас
есть доступ к Intellisense. Недостатком является то, что это может вызвать
конфликтные проблемы на других компьютерах.

Лучше всего использовать раннюю привязку при написании кода,
а затем использовать позднюю привязку при распространении кода другим
пользователям.

Позднее связывание

Позднее связывание означает, что мы создаем объект во время
выполнения.

Мы объявляем переменную как тип «Объект». Затем мы
используем CreateObject для создания объекта.

Sub PozdSvyaz()

    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    
End Sub

Использование Dim с Arrays

В VBA есть два типа массивов:

  1. Статический — размер массива задается в
    операторе Dim и не может изменяться.
  2. Динамический — размер массива не указан в
    выражении Dim. Это устанавливается позже с помощью оператора ReDim
' Статический массив

' Магазины 7 длинных - от 0 до 6
Dim arrLong(0 To 6) As Long

' Магазины 7 длинных - от 0 до 6
Dim arrLong(6) As String

Динамический массив дает нам гораздо больше гибкости. Мы
можем установить размер во время выполнения кода.

Мы объявляем динамический массив, используя инструкцию Dim,
и устанавливаем размер позже, используя ReDim.

' Динамический массив

' Объявите переменную
Dim arrLong() As Long

' Установить размер
ReDim arrLong(0 To 6) As Long

Использование ReDim

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

Sub IspSet()

    ' Объявите переменную
    Dim arrLong() As Long
    
    ' Спросите пользователя о размере
    Dim size As Long
    size = InputBox("Пожалуйста, введите размер массива.", Default:=1)
    
    ' Установите размер на основе пользовательского ввода
    ReDim arrLong(0 To size) As Long

End Sub

На самом деле мы можем использовать оператор Redim без
предварительного использования оператора Dim.

В первом примере вы можете видеть, что мы используем Dim:

Sub IspDimReDim()

    ' Использование Dim
    Dim arr() As String

    ReDim arr(1 To 5) As String
    
    arr(1) = "Яблоко"
    arr(5) = "Апельсин"
    
End Sub

Во втором примере мы не используем Dim:

Sub IspTolkoReDim ()

    ' Использование только ReDim
    ReDim arr(1 To 5) As String
    
    arr(1) = "Яблоко"
    arr(5) = "Апельсин"
    
End Sub

Преимущество состоит в том, что вам не нужно тусклое
утверждение. Недостатком является то, что это может сбить с толку тех, кто
читает ваш код. В любом случае это не имеет большого значения.

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

Вы можете найти все, что вам нужно знать о массивах в VBA здесь.

Устранение неполадок ошибок  Dim

В таблице
ниже приведены ошибки, с которыми вы можете столкнуться при использовании Dim. См. Ошибки VBA для
объяснения различных типов ошибок.

Ошибка Тип Причина
Массив уже
рассчитан
Компиляция Использование
Redim для
статического
массива.
Ожидаемый:
идентификатор
Синтаксис Использование
зарезервированного слова в качестве
имени переменной.
Ожидаемый:
новый тип имени
Синтаксис Тип отсутствует в
выражении Dim.
Переменная объекта или переменная
блока не
установлена
Время выполнения New не был
использован для
создания объекта.
Переменная объекта или переменная
блока
не установлена
Время выполнения Set не использовался для назначения
переменной объекта.
Пользовательский
тип не определен
Компиляция Тип не распознан.
Это может
произойти, если
ссылочный файл не добавлен в меню
«Инструменты->
Ссылка» или имя
модуля класса
написано
неправильно.
Недопустимый
оператор вне блока
Type
Компиляция Имя переменной
отсутствует в
выражении Dim
Переменная
не определена
Компиляция Переменная
используется перед Dim-строкой.

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

Когда мы используем Dim в процедуре (то есть подпрограмме или функции), она считается
локальной. Это означает, что это доступно только с этой процедурой.

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

В приведенном ниже коде мы объявили count как глобальную переменную:

' Глобальная
Dim count As Long
Sub UseCount1()
    count = 6
End Sub
Sub UseCount2()
    count = 4
End Sub

Что произойдет, если у нас будет глобальная переменная и
локальная переменная с одинаковым именем?

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

' Глобальная
Dim count As Long

Sub UseCount()
    ' Локальная
    Dim count As Long
    
    ' Относится к локальному счету
    count = 6
    
End Sub

Подобная ситуация может привести только к проблемам, так как
трудно отследить, какой счет используется.

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

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

Dim против Private

В VBA есть ключевое слово Private.

Если мы используем ключевое слово Private с переменной или
подфункцией / функцией, то этот элемент доступен только в текущем модуле.

Использование Dim и Private для переменной дает тот же
результат

' Доступно во всем этом модуле
Private priCount As Long
Dim dimCount As Long

Sub UseCount()

    ' Доступно только в этом разделе
    Private priName As String
    Dim dimName As String
    
End Sub

В VBA принято использовать Private для глобальных переменных
и Dim для локальных

' Доступно во всем этом модуле
Private priCount As Long

Sub UseCount()
    ' Только локальный
    Dim dimName As String
    
End Sub

Local OnlyThere
в VBA есть 2 других
типа объявлений, которые называются Public и Global.

Ниже приводится краткое изложение всех 4 типов:

  1. Dim
    — используется для объявления локальных переменных, т. Е. В процедурах.
  2. Private
    — используется для объявления глобальных переменных и процедур. Эти переменные
    доступны только для текущего модуля.
  3. Public
    — используется для объявления глобальных переменных и процедур. Эти переменные
    доступны во всех модулях.
  4. Global
    — старая и устаревшая версия Public.
    Может использоваться только в стандартных модулях. Он существует только для обратной
    совместимости.

Заключение

На этом мы заканчиваем статью о VBA Dim Statement. Если у вас есть
какие-либо вопросы или мысли, пожалуйста, дайте мне знать в комментариях ниже.

“One man’s constant is another man’s variable.” – Alan Perlis

This post provides a complete guide to using the VBA Dim statement.

The first section provides a quick guide to using the Dim statement including examples and the format of the Dim statement.

The rest of the post provides the most complete guide you will find on the VBA Dim Statement.

If you are interested in declaring parameters then you can read about them here.

A Quick Guide to using the VBA Dim Statement

Description Format Example
Basic variable Dim [variable name] As [Type] Dim count As Long
Dim amount As Currency
Dim name As String
Dim visible As Boolean
Fixed String Dim [variable name] As String * [size] Dim s As String * 4
Dim t As String * 10
Variant Dim [variable name] As Variant
Dim [variable name]
Dim var As Variant
Dim var
Object using Dim and New Dim [variable name] As New [object type] Dim coll As New Collection
Dim coll As New Class1
Object using Dim, Set and New Dim [variable name] As [object type]
Set [variable name] = New [object type]
Dim coll As Collection
Set coll = New Collection

Dim coll As Class1
Set coll = New Class1

Static array Dim [variable name]([first] To [last] ) As [Type] Dim arr(1 To 6) As Long
Dynamic array Dim [variable name]() As [Type]
ReDim [variable name]([first] To [last])
Dim arr() As Long
ReDim arr(1 To 6)
External Library
(Early Binding)*
Dim [variable name] As New [item] Dim dict As New Dictionary
External Library
(Early Binding using Set)*
Dim [variable name] As [item]
Set [variable name] = New [item]
Dim dict As Dictionary
Set dict = New Dictonary
External Library
(Late Binding)
Dim [variable name] As Object
Set [variable name] = CreateObject(«[library]»)
Dim dict As Object
Set dict = CreateObject(«Scripting.Dictionary»)

*Note: Early binding requires that you add the reference file using Tools->References from the menu. See here for how to add the Dictonary reference.

Useful Links

Declaring parameters in a sub or function
Using Objects in VBA
VBA Arrays
VBA Collection
VBA Dictionary
VBA Workbook
VBA Worksheet

What is the VBA Dim Statement

The Dim keyword is short for Dimension. It is used to declare variables in VBA.

Declare means we are telling VBA about a variable we will use later.

There are four types of Dim statements. They are all pretty similar in terms of syntax.

They are:

  1. Basic variable
  2. Variant
  3. Object
  4. Array

The following is a brief description of each type:

    1. Basic variable – this variable type holds one value. These are the types such as Long, String, Date, Double, Currency.
    1. Variant – VBA decides at runtime which type will be used. You should avoid variants where possible but in certain cases it is a requirement to use them.
    1. Object – This is a variable that can have multiple methods(i.e. subs/functions) and multiple properties(i.e. values). There are 3 kinds:
      1. Excel objects such as the Workbook, Worksheet and Range objects.
      2. User objects created using Class Modules.
      3. External libraries such as the Dictionary.
  1. Array – this is a group of variables or objects.

In the next section, we will look at the format of the VBA Dim statement with some examples of each.

In later sections we will look at each type in more detail.

Format of the VBA Dim Statement

The format of the Dim statement is shown below

' 1. BASIC VARIABLE
' Declaring a basic variable
Dim [variable name] As [type]

' Declaring a fixed string
Dim [variable name] As String * [size]

' 2. VARIANT
Dim [variable name] As Variant
Dim [variable name]

' 3. OBJECT
' Declaring an object
Dim [variable name] As [type]

' Declaring and creating an object
Dim [variable name] As New [type]

' Declaring an object using late binding
Dim [variable name] As Object

' 4. ARRAY
' Declaring a static array
Dim [variable name](first To last) As [type]

' Declaring a dynamic array
Dim [variable name]() As [type]

Below are examples of using the different formats

' https://excelmacromastery.com/
Sub Examples()

    ' 1. BASIC VARIABLE
    ' Declaring a basic variable
    Dim name As String
    Dim count As Long
    Dim amount As Currency
    Dim eventdate As Date
    
    ' Declaring a fixed string
    Dim userid As String * 8
    
    ' 2. VARIANT
    Dim var As Variant
    Dim var
    
    ' 3. OBJECT
    ' Declaring an object
    Dim sh As Worksheet
    Dim wk As Workbook
    Dim rg As Range
    
    ' Declaring and creating an object
    Dim coll1 As New Collection
    Dim o1 As New Class1
    
    ' Declaring an object - create object below using Set
    Dim coll2 As Collection
    Dim o2 As Class1
    
    Set coll2 = New Collection
    Set o2 = New Class1
    
    ' Declaring and assigning using late binding
    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    
    ' 4. ARRAY
    ' Declaring a static array
    Dim arrScores(1 To 5) As Long
    Dim arrCountries(0 To 9) As String
    
    ' Declaring a dynamic array - set size below using ReDim
    Dim arrMarks() As Long
    Dim arrNames() As String
    
    ReDim arrMarks(1 To 10) As Long
    ReDim arrNames(1 To 10) As String

End Sub

We will examine these different types of Dim statements in the later sections.

How to Use Dim with Multiple Variables

We can declare multiple variables in a single Dim statement

Dim name As String, age As Long, count As Long

If we leave out the type then VBA automatically sets the type to be a Variant. We will see more about Variant later.

' Amount is a variant
Dim amount As Variant

' Amount is a variant
Dim amount

' Address is a variant - name is a string
Dim name As String, address

' name is a variant, address is a string
Dim name, address As String

When you declare multiple variables you should specify the type of each one individually

Dim wk As Workbook, marks As Long, name As String

You can place as many variables as you like in one Dim statement but it is good to keep it to 3 or 4 for readability.

Where Should I Put the Dim Statement?

The Dim statement can be placed anywhere in a procedure. However, it must come before any line where the variable is used.

If the variable is used before the Dim statement then you will get a “variable not defined” error:

When it comes to the positioning your Dim statements you can do it in two main ways. You can place all your Dim statements at the top of the procedure:

' https://excelmacromastery.com/
Sub DimTop()

    ' Placing all the Dim statements at the top
    Dim count As Long, name As String, i As Long
    Dim wk As Workbook, sh As Worksheet, rg As Range
    
    Set wk = Workbooks.Open("C:Docsdata.xlsx")
    Set sh = wk.Worksheets(1)
    Set rg = sh.Range("A1:A10")
    
    For i = 1 To rg.Rows.count
        count = rg.Value
        Debug.Print count
    Next i
  
End Sub

OR you can declare the variables immediately before you use them:

' https://excelmacromastery.com/
Sub DimAsUsed()

    Dim wk As Workbook
    Set wk = Workbooks.Open("C:Docsdata.xlsx")
    
    Dim sh As Worksheet
    Set sh = wk.Worksheets(1)
    
    Dim rg As Range
    Set rg = sh.Range("A1:A10")
    
    Dim i As Long, count As Long, name As String
    For i = 1 To rg.Rows.count
        count = rg.Value
        name = rg.Offset(0, 1).Value
        Debug.Print name, count
    Next i
  
End Sub

I personally prefer the latter as it makes the code neater and it is easier to read, update and spot errors.

Using Dim in Loops

Placing a Dim statement in a Loop has no effect on the variable.

When VBA starts a Sub (or Function), the first thing it does is to create all the variables that have been declared in the Dim statements.

The following 2 pieces of code are almost the same. In the first, the variable Count is declared before the loop. In the second it is declared within the loop.

' https://excelmacromastery.com/
Sub CountOutsideLoop()

    Dim count As Long

    Dim i As Long
    For i = 1 To 3
        count = count + 1
    Next i
    
    ' count value will be 3
    Debug.Print count

End Sub
' https://excelmacromastery.com/
Sub CountInsideLoop()

    Dim i As Long
    For i = 1 To 3
        Dim count As Long
        count = count + 1
    Next i
    
    ' count value will be 3
    Debug.Print count

End Sub

The code will behave exactly the same because VBA will create the variables when it enters the sub.

Can I use Dim to Assign a Value?

In languages like C++, C# and Java, we can declare and assign variables on the same line

' C++
int i = 6
String name = "John"

We cannot do this in VBA. We can use the colon operator to place the declare and assign lines on the same line.

Dim count As Long: count = 6

We are not declaring and assigning in the same VBA line. What we are doing is placing these two lines(below) on one line in the editor. As far as VBA is concerned they are two separate lines as here:

Dim count As Long
count = 6

Here we put 3 lines of code on one editor line using the colon:

count = 1: count = 2: Set wk = ThisWorkbook

There is really no advantage or disadvantage to assigning and declaring on one editor line. It comes down to a personal preference.

Is Dim Actually Required?

The answer is that it is not required. VBA does not require you to use the Dim Statement.

However, not using the Dim statement is a poor practice and can lead to lots of problems.

You can use a variable without first using the Dim statement. In this case the variable will automatically be a variant type.

This can lead to problems such as

  1. All variables are variants (see the Variant section for issues with this).
  2. Some variable errors will go undetected.

Because of these problems it is good practice to make using Dim mandatory in our code. We do this by using the Option Explicit statement.

Option Explicit

We can make Dim mandatory in a module by typing “Option Explicit” at the top of a module.

We can make this happen automatically in each new module by selecting Tools->Options from the menu and checking the box beside “Require Variable Declaration”. Then when you insert a new module, “Option Explicit” will be automatically added to the top.

VBA Require Variable Declaration

Let’s look at some of the errors that may go undetected if we don’t use Dim.

Variable Errors

In the code below we use the Total variable without using a Dim statement

' https://excelmacromastery.com/
Sub NoDim()

    Total = 6
    
    Total = Total + 1
    
    Debug.Print Total

End Sub

If we accidentally spell Total incorrectly then VBA will consider it a new variable.

In the code below we have misspelt the variable Total as Totall:

' https://excelmacromastery.com/
Sub NoDimError()

    Total = 6
    
    ' The first Total is misspelt
    Totall = Total + 1
    
    ' This will print 6 instead of 7
    Debug.Print Total

End Sub

VBA will not detect any error in the code and an incorrect value will be printed.

Let’s add Option Explicit and try the above code again

' https://excelmacromastery.com/
Option Explicit 

Sub NoDimError()

    Total = 6
    
    ' The first Total is misspelt
    Totall = Total + 1
    
    ' This will print 6 instead of 7
    Debug.Print Total

End Sub

Now when we run the code we will get the “Variable not defined” error. To stop this error appearing we must use Dim for each variable we want to use.

When we add the Dim statement for Total and run the code we will now get an error telling us that the misspelt Totall was not defined.

variable not defined 2

This is really useful as it helps us find an error that would have otherwise gone undetected.

Keyword Misspelt Error

Here is a second example which is more subtle.

When the following code runs it should change the font in cell A1 to blue.

However, when the code runs nothing happens.

' https://excelmacromastery.com/
Sub SetColor()

    Sheet1.Range("A1").Font.Color = rgblue

End Sub

The error here is that rgblue should be rgbBlue. If you add Option Explicit to the module, the error “variable not defined” will appear. This makes solving the problem much easier.

These two examples are very simple. If you have a lot of code then errors like this can be a nightmare to track down.

Using Dim with Basic Variables

VBA has the same basic variable types that are used in the Excel Spreadsheet.

You can see a list of all the VBA variable types here.

However, most of the time you will use the following ones

Type Storage Range Description
Boolean 2 bytes True or False This variable can be either True or False.
Long 4 bytes -2,147,483,648 to 2,147,483,647 Long is short for Long Integer. Use this instead of the Integer* type.
Currency 8 bytes -1.79769313486231E308 to-4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values Similar to Double but has only 4 decimal places
Double 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
String varies 0 to approximately 2 billion Holds text.

*Originally we would use the Long type instead of Integer because the Integer was 16-bit and so the range was -32,768 to 32,767 which is quite small for a lot of the uses of integer.

However on a 32 bit(or higher) system the Integer is automatically converted to a Long. As Windows has been 32 bit since Windows 95NT there is no point in using an Integer.

In a nutshell, always use Long for an integer type in VBA.

Fixed String Type

There is one unusual basic variable type in VBA that you may not be familiar with.

This is the fixed string type. When we create a normal string in VBA we can add text and VBA will automatically resize the string for us

' https://excelmacromastery.com/
Sub StringType()

    Dim s As String
    
    ' s is "John Smith"
    s = "John Smith"
    
    ' s is "Tom"
    s = "Tom"

End Sub

A fixed string is never resized. This string will always be the same size no matter what you assign to it

Here are some examples

' https://excelmacromastery.com/
Sub FixedString()
    
    Dim s As String * 4
    
    ' s is "John"
    s = "John Smith"
    
    ' s = "Tom "
    s = "Tom"

End Sub

Using Dim with Variants

When we declare a variable to be a variant, VBA will decide at runtime which variable type it should be.

We declare variants as follows

' Both are variants
Dim count
Dim count As Variant

This sounds like a great idea in theory. No more worrying about the variable type

' https://excelmacromastery.com/
Sub UsingVariants()
    
    Dim count As Variant
        
    count = 7
    
    count = "John"
    
    count = #12/1/2018#

End Sub

However, using variants is poor practice and this is why:

  1. Runtime Errors – VBA will not notice incorrect type errors(i.e. Data Mismatch).
  2. Compile Errors – VBA cannot detect compile errors.
  3. Intellisense is not available.
  4. Size – A variant is set to 16 bytes which is the largest variable type

Runtime Errors

Errors are your friend!

They may be annoying and frustrating when they happen but they are alerting you to future problems which may not be so easy to find.

The Type Mismatch error alerts you when incorrect data is used.

For example. Imagine we have a sheet of student marks. If someone accidentally(or deliberately) replaces a mark with text then the data is invalid.

If we use a variant to store marks then no error will occur:

' https://excelmacromastery.com/
Sub MarksVariant()
    
    Dim mark As Variant
    
    Dim i As Long
    For i = 1 To 10
        
        ' Read the mark
        mark = Sheet1.Range("A" & i).Value
        
    Next

End Sub

This is not good because there is an error with your data and you are not aware of it.

If you make the variable Long then VBA will alert you with a “Type Mismatch” error if the values are text.

' https://excelmacromastery.com/
Sub MarksLong()
    
    Dim mark As Long
    
    Dim i As Long
    For i = 1 To 10
        
        ' Read the mark
        mark = Sheet1.Range("A" & i).Value
        
    Next

End Sub

Compile Errors

Using the compiler to check for errors is very efficient. It will check all of your code for problems before you run it. You use the compiler by selecting Debug->Compile VBAProject from the menu.

In the following code, there is an error. The Square function expects a long integer but we are passing a string(i.e. the name variable):

' https://excelmacromastery.com/
Sub CompileError()

    Dim name As String

    Debug.Print Square(name)

End Sub

Function Square(value As Long) As Long
    Square = value * value
End Function

If we use Debug->Compile on this code, VBA will show us an error:

dim compile error

This is good news as we can fix this error right away. However, if we declare the value parameter as a variant:

Function Square(value As Variant) As Long
    Square = value * value
End Function

then Debug.Compile will not treat this as an error. The error is still there but it is undetected.

Accessing the Intellisense

The Intellisense is an amazing feature of VBA. It gives you the available options based on the type you have created.

Imagine you declare a worksheet variable using Dim

Dim wk As Workbook

When you use the variable wk with a decimal point, VBA will automatically display the available options for the variable.

You can see the Intellisense in the screenshot below

VBA Intellisense

If you use Variant as a type then the Intellisense will not be available

Dim wk As Variant

This is because VBA will not know the variable type until runtime.

Variant Size

The size of a variant is 16 bytes. If the variable is going to be a long then it would only take up 4 bytes. You can see that this is not very efficient.

However, unlike the 1990’s where this would be an issue, we now have computers with lots of memory and it is unlikely you will notice an inefficiency unless you are using a huge amount of variables.

Using Dim with Objects

If you don’t know what Objects are then you can read my article about VBA Objects here.

There are 3 types of objects:

  1. Excel objects
  2. Class Module objects
  3. External library objects

Note: The VBA Collection object is used in a similar way to how we use Class Module object. We use new to create it.

Let’s look at each of these in turn.

Excel objects

Excel objects such as the Workbook, Worksheet, Range, etc. do not use New because they are automatically created by Excel. See When New is not required.

When a workbook is created or opened then Excel automatically creates the associated object.

For example, in the code below we open a workbook. VBA will create the object and the Open function will return a workbook which we can store in a variable

' https://excelmacromastery.com/
Sub OpenWorkbook()
    
    Dim wk As Workbook
    Set wk = Workbooks.Open("C:Docsdata.xlsx")

End Sub

If we create a new worksheet, a similar thing happens. VBA will automatically create it and provide use access to the object.

' https://excelmacromastery.com/
Sub AddSheet()
    
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Worksheets.Add

End Sub

We don’t need to use the New keyword for these Excel objects.

We just assign the variable to the function that either creates a new object or that gives us access to an existing one.

Here are some examples of assigning the Workbook, Worksheet and range variables:

' https://excelmacromastery.com/
Sub DimWorkbook()
    
    Dim wk As Workbook
    
    ' assign wk to a new workbook
    Set wk = Workbooks.Add
    
    ' assign wk to the first workbook opened
    Set wk = Workbooks(1)
    
    ' assign wk to The workbook Data.xlsx
    Set wk = Workbooks("Data.xlsx")
    
    ' assign wk to the active workbook
    Set wk = ActiveWorkbook
    
End Sub
' https://excelmacromastery.com/
Sub DimWorksheet()
    
    Dim sh As Worksheet
    
    ' Assign sh to a new worksheet
    Set sh = ThisWorkbook.Worksheets.Add
    
    ' Assign sh to the leftmost worksheet
    Set sh = ThisWorkbook.Worksheets(1)
    
    ' Assign sh to a worksheet called Customers
    Set sh = ThisWorkbook.Worksheets("Customers")
    
    ' Assign sh to the active worksheet
    Set sh = ActiveSheet

End Sub
' https://excelmacromastery.com/
Sub DimRange()

    ' Get the customer worksheet
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Worksheets("Customers")
    
    ' Declare the range variable
    Dim rg As Range
    
    ' Assign rg to range A1
    Set rg = sh.Range("A1")
    
    ' Assign rg to range B4 to F10
    Set rg = sh.Range("B4:F10")
    
    ' Assign rg to range E1
    Set rg = sh.Cells(1, 5)
    
End Sub

If you want to know more about these objects you can check out these articles: VBA Workbook, VBA Worksheet and VBA Ranges and Cells.

Using Dim with Class Module Objects

In VBA we use Class Modules to create our own custom objects. You can read all about Class Modules here.

If we are creating an object then we need to use the New keyword.

We can do this in the Dim statement or in the Set statement.

The following code creates an object using the New keyword in the Dim statement:

' Declare and create
Dim o As New class1
Dim coll As New Collection

Using New in a Dim statement means that exactly one object will be created each time our code runs.

Using Set gives us more flexibility. We can create many objects from one variable. We can also create an object based on a condition.

This following code shows how we create a Class Module object using Set.

(To create a Class Module, go to the project window, right-click on the appropiate workbook and select “Insert Class Module”. See Creating a Simple Class Module for more details.)

' Declare only
Dim o As Class1

' Create using Set
Set o = New Class1

Let’s look at an example of using Set. In the code below we want to read through a range of data. We only create an object if the value is greater than 50.

We use Set to create the Class1 object. This is because the number of objects we need depends on the number of values over 50.

' https://excelmacromastery.com/
Sub UsingSet()
    
    ' Declare a Class1 object variable
    Dim o As Class1
    
    ' Read a range
    Dim i As Long
    For i = 1 To 10
        If Sheet1.Range("A" & i).Value > 50 Then

            ' Create object if condition met
            Set o = New Class1
            
        End If
    Next i

End Sub

I’ve kept this example simple for clarity. In a real-world version of this code we would fill the Class Module object with data and add it to a data structure like a Collection or Dictionary.

Here is an example of a real-world version based on the data below:

dim sample data

' Class Module - clsStudent
Public Name As String
Public Subject As String

' Standard Module
' https://excelmacromastery.com/
Sub ReadMarks()

    ' Create a collection to store the objects
    Dim coll As New Collection
    
    ' Current Region gets the adjacent data
    Dim rg As Range
    Set rg = Sheet1.Range("A1").CurrentRegion
    
    Dim i As Long, oStudent As clsStudent
    For i = 2 To rg.Rows.Count
        
        ' Check value
        If rg.Cells(i, 1).Value > 50 Then
            ' Create the new object
            Set oStudent = New clsStudent
            
            ' Read data to the student object
            oStudent.Name = rg.Cells(i, 2).Value
            oStudent.Subject = rg.Cells(i, 3).Value
            
            ' add the object to the collection
            coll.Add oStudent
            
        End If
        
    Next i
    
    ' Print the data to the Immediate Window to test it
    Dim oData As clsStudent
    For Each oData In coll
        Debug.Print oData.Name & " studies " & oData.Subject
    Next oData

End Sub

To learn more about Set you can check out here.

Objects from an External Library

A really useful thing we can do with VBA is to access external libraries. This opens up a whole new world to what we can do.

Examples are the Access, Outlook and Word libraries that allow us to communicate with these applications.

We can use libraries for different types of data structures such as the Dictionary, the Arraylist, Stack and Queue.

There are libraries for scraping a website (Microsoft HTML Object Library), using Regular Expressions (Microsoft VBScript Regular Expressions) and many other tasks.

We can create these objects in two ways:

  1. Early Binding
  2. Late Binding

Let’s look at these in turn.

Early Binding

Early binding means that we add a reference file. Once this file is added we can treat the object like a class module object.

We add a reference using Tools->Reference and then we check the appropriate file in the list.

For example, to use the Dictionary we place a check on “Microsoft Scripting Runtime”:

vba references dialog

Once we have the reference added we can use the Dictionary like a class module object

' https://excelmacromastery.com/
Sub EarlyBinding()

    ' Use Dim only
    Dim dict1 As New Dictionary
    
    ' Use Dim and Set
    Dim dict2 As Dictionary
    Set dict2 = New Dictionary

End Sub

The advantage of early binding is that we have access to the Intellisense. The disadvantage is that it may cause conflict issues on other computers.

The best thing to do is to use early binding when writing the code and then use late binding if distributing your code to other users.

Late Binding

Late binding means that we create the object at runtime.

We declare the variable as an “Object” type. Then we use CreateObject to create the object.

' https://excelmacromastery.com/
Sub LateBinding()

    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    
End Sub

Using Dim with Arrays

There are two types of arrays in VBA. They are:

  1. Static – the array size is set in the Dim statement and it cannot change.
  2. Dynamic – the array size is not set in the Dim statement. It is set later using the ReDim statement.
' STATIC ARRAY

' Stores 7 Longs - 0 to 6
Dim arrLong(0 To 6) As Long

' Stores 7 Strings - 0 to 6
Dim arrLong(6) As String

A dynamic array gives us much more flexibility. We can set the size while the code is running.

We declare a dynamic array using the Dim statement and we set the size later using ReDim.

' DYNAMIC ARRAY

' Declare the variable
Dim arrLong() As Long

' Set the size
ReDim arrLong(0 To 6) As Long

Using ReDim

The big difference between Dim and ReDim is that we can use a variable in the ReDim statement. In the Dim statement, the size must be a constant value.

' https://excelmacromastery.com/
Sub UserSet()

    ' Declare the variable
    Dim arrLong() As Long
    
    ' Ask the user for the size
    Dim size As Long
    size = InputBox("Please enter the size of the array.", Default:=1)
    
    ' Set the size based on the user input
    ReDim arrLong(0 To size) As Long

End Sub

We can actually use the Redim Statement without having first used the Dim statement.

In the first example you can see that we use Dim:

' https://excelmacromastery.com/
Sub UsingDimReDim()

    ' Using Dim
    Dim arr() As String

    ReDim arr(1 To 5) As String
    
    arr(1) = "Apple"
    arr(5) = "Orange"
    
End Sub

In the second example we don’t use Dim:

' https://excelmacromastery.com/
Sub UsingReDimOnly()

    ' Using  ReDim only
    ReDim arr(1 To 5) As String
    
    arr(1) = "Apple"
    arr(5) = "Orange"
    
End Sub

The advantage is that you don’t need the Dim statement. The disadvantage is that it may confuse someone reading your code. Either way it doesn’t make much difference.

You can use the Preserve keyword with ReDim to keep existing data while you resize an array. You can read more about this here here.

You can find everything you need to know about arrays in VBA here.

Troubleshooting Dim Errors

The table below shows the errors that you may encounter when using Dim. See VBA Errors for an explanation of the different error types.

Error Type Cause
Array already dimensioned Compile Using Redim on an array that is static
Expected: identifier Syntax Using a reserved word as the variable name
Expected: New of type name Syntax The type is missing from the Dim statement
Object variable or With block variable not set Runtime New was not used to create the object(see Creating an Object)
Object variable or With block variable not set Runtime Set was not used to assign an object variable.
User-defined type not defined Compile The type is not recognised. Can happen if a reference file is not added under Tools->Reference or the Class Module name is spelled wrong.
Statement invalid outside Type block Compile Variable name is missing from the Dim statement
Variable not defined Compile The variable is used before the Dim line.

Local versus Module versus Global Variables

When we use Dim in a procedure (i.e. a Sub or Function), it is considered to be local. This means it is only available in the procedure where it is used.

The following are the different types of variables found in VBA:

  • Local variables are variables that are available to the procedure only. Local variables are declared using the Dim keyword.
  • Module variables are variables that are only available in the current module only. Module variables are declared using the Private keyword.
  • Global variables are variables that are available to the entire project. Global variables are declared using the Public keyword.

In the code below we have declared count as a global variable:

 ' Global
 ' https://excelmacromastery.com/
 Public count As Long

 Sub UseCount1()

    count = 6
    
 End Sub

 Sub UseCount2()

    count = 4
    
 End Sub

What happens if we have a global variable and a local variable with the same name?

It doesn’t actually cause an error. VBA gives the local declaration precedence:

 ' https://excelmacromastery.com/

 ' Global
 Public count As Long 

 Sub UseCount()
    ' Local
    Dim count As Long
    
    ' Refers to the local count
    count = 6
    
 End Sub

Having a situation like this can only lead to trouble as it is difficult to track which count is being used.

In general global variables should be avoided. They make the code very difficult to read because their values can be changed anywhere in the code. This makes errors difficult to spot and resolve.

The one use of a global variable is retaining a value between code runs. This can be useful for certain applications where you want to ‘remember’ a value after the code has stopped running.

In the code below we have a sub called Update. Each time we run the Update sub(using Run->Run Sub from the menu or F5) it will add 5 to the amount variable and print the result to the Immediate Window(Ctrl + G to view this window):

 Public amount As Long

 Sub Update()
    amount = amount + 5
    Debug.Print "Update: " & amount
 End Sub

The results are:

First run: amount = 5

Second run: amount = 10

Third run: amount = 15

and so on.

If we want to clear all global variable values then we can use the End keyword. Note that the End keyword will stop the code and reset all variables so you should only use it as the last line in your code.

Here is an example of using the End keyword:

Sub ResetAllGlobals()
    End ' Resets all variables and ends the current code run
End Sub

Dim versus Private versus Public

We can declare variables using Public, Private and Dim. In some cases, they can be used interchangeably.

However, the following is the convention we use for each of the declaration keywords:

  1. Dim – used to declare local variables i.e. available only in the current procedure.
  2. Private – used to declare module variables and procedures. These are available within the current module only.
  3. Public – used to declare global variables and procedures. These are available throughout the project.
  4. Global(obsolete) – an older and obsolete version of Public. Can only be used in standard modules. It only exists for backward compatibility.

Note the Public and Private keywords are also used within Class Modules.

Conclusion

This concludes the article on the VBA Dim Statement. If you have any questions or thoughts then please let me know in the comments below.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Dim statement (VBA)

vblr6.chm1008897

vblr6.chm1008897

office

674a6797-5827-9ce6-6375-e24b21977a6d

05/24/2019

medium

Declares variables and allocates storage space.

Syntax

Dim [ WithEvents ] varname [ ( [ subscripts ] ) ] [ As [ New ] type ] [ , [ WithEvents ] varname [ ( [ subscripts ] ) ] [ As [ New ] type ]] . . .

The Dim statement syntax has these parts:

Part Description
WithEvents Optional. Keyword that specifies that varname is an object variable used to respond to events triggered by an ActiveX object. WithEvents is valid only in class modules. You can declare as many individual variables as you like by using WithEvents, but you can’t create arrays with WithEvents. You can’t use New with WithEvents.
varname Required. Name of the variable; follows standard variable naming conventions.
subscripts Optional. Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax: [ lower To ] upper [ , [ lower To ] upper ] . . ..

When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.

New Optional. Keyword that enables implicit creation of an object. If you use New when declaring the object variable, a new instance of the object is created on first reference to it, so you don’t have to use the Set statement to assign the object reference.

The New keyword can’t be used to declare variables of any intrinsic data type or to declare instances of dependent objects, and it can’t be used with WithEvents.

type Optional. Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (for variable-length strings), String length (for fixed-length strings), Object, Variant, a user-defined type, or an object type. Use a separate As type clause for each variable you declare.

Remarks

Variables declared with Dim at the module level are available to all procedures within the module. At the procedure level, variables are available only within the procedure.

Use the Dim statement at the module or procedure level to declare the data type of a variable. For example, the following statement declares a variable as an Integer.

Dim NumberOfEmployees As Integer 

Also use a Dim statement to declare the object type of a variable. The following declares a variable for a new instance of a worksheet.

If the New keyword is not used when declaring an object variable, the variable that refers to the object must be assigned an existing object by using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it doesn’t refer to any particular instance of an object.

You can also use the Dim statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs.

If you don’t specify a data type or object type, and there is no Def_type_ statement in the module, the variable is Variant by default.
When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string («»), and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable.

[!NOTE]
When you use the Dim statement in a procedure, you generally put the Dim statement at the beginning of the procedure.

Example

This example shows the Dim statement used to declare variables. It also shows the Dim statement used to declare arrays. The default lower bound for array subscripts is 0 and can be overridden at the module level by using the Option Base statement.

' AnyValue and MyValue are declared as Variant by default with values 
' set to Empty. 
Dim AnyValue, MyValue 
 
' Explicitly declare a variable of type Integer. 
Dim Number As Integer 
 
' Multiple declarations on a single line. AnotherVar is of type Variant 
' because its type is omitted. 
Dim AnotherVar, Choice As Boolean, BirthDate As Date 
 
' DayArray is an array of Variants with 51 elements indexed, from 
' 0 thru 50, assuming Option Base is set to 0 (default) for 
' the current module. 
Dim DayArray(50) 
 
' Matrix is a two-dimensional array of integers. 
Dim Matrix(3, 4)As Integer 
 
' MyMatrix is a three-dimensional array of doubles with explicit 
' bounds. 
Dim MyMatrix(1 To 5, 4 To 9, 3 To 5)As Double 
 
' BirthDay is an array of dates with indexes from 1 to 10. 
Dim BirthDay(1 To 10)As Date 
 
' MyArray is a dynamic array of variants. 
Dim MyArray()

See also

  • Data types
  • Statements

[!includeSupport and feedback]

Хитрости »

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


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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

Dim MyVar1, MyVar2, MyVar3 As Integer

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

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

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

Dim MyVar1%, MyVar2%, MyVar3%

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

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

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

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

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

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

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

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

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

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

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

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

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

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

DefBool B
Sub test()
    Dim bCheck
End Sub

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

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

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

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

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

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

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

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

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

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

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

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


Константы

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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


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



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

Home / VBA / VBA Dim Statement

What is the VBA DIM Statement?

VBA DIM statement stands for “declare” that you must use when you need to declare a variable. When you use it, it tells VBA that you are declaring a specific name as a variable as assigning a specific data type to it. It can be used to declare the following:

  • Basic Variables
  • Variants
  • Objects
  • Array
  1. Type the keyword “Dim” at the start.
  2. After that, enter the name of the variable that you want to use.
  3. Next, you need to use the word “as” and you’ll get an instant list of data types.
  4. In the end, choose the data type that you want to assign to the variable.

As I said when you declare a variable you need to assign a data type with that. See the following snapshot.

Declaring Multiple Variables with One Dim Statement

When you need to declare more than one variable you can do that by using the Dim statement for a single time. Consider the following example.

Using Option Explicit

This is highly recommended to declare all the variable which makes your code perform better and increase the efficiency as well. But if you skip declaring a variable and then use it in a code, VBA will take that variable as a variant.

The best way to never miss to declare a variable is to use the Option Explicit statement that forces you to declare a variable and shows an error every time you miss it.

Dim Statement with Arrays

You need to use the DIM statement when you need to declare an array as well. Consider the following example that I have shared.

In the above example, you have two arrays that have been declared with the dim statement.

In the first array, you have three items and in the second, there’s no item declared. Here’s the point when you need to declare an array you need to use parentheses to declare items of the array and blank parentheses if you want a dynamic array.

Use DIM with Excel Objects

You can also refer to an object using the DIM statement. Let’s say you want to count sheets from a workbook, you can declare that an object and count the worksheet from it.

In the above example, you have declared wb as a workbook then set the workbook “book1” to use it further in the code.

Where to Put the Dim Statement?

You can use declare a variable using the DIM statement anywhere within the code but, make sure to declare it before you use it. So let’s say you are referring to a variable in line 2 of the code and you have used the Dim in line 3 to declare, well, you going to get an error.

So, make sure to declare a variable before you want to use it.

Skip to content

VBA Data Types: How to Declare (Dim) and Set VBA Variables

VBA Data Types: How to Declare (Dim) and Set VBA Variables

A variable in programming is like a variable in math: it stands in the place of a value, and that value can change.

This is extremely useful when writing VBA code.

Declaring variables means telling Excel what data type will go into the variable 💡

So, when declaring variables it’s essential to know which VBA data type to choose for your variable.

Read on and learn why it’s so important to declare a variable, and how to actually do it.

Variable declaration (VBA dim): How and why

In VBA, declaring has two steps:

  1. Set a name for the VBA variable. For example, you might give your numbers variable, the “quarterlySales” variable name.
  2. Set a type for the VBA variable. We’ll go over types in more detail in the next section. For now, just think of type as telling Excel what sort of data you’re going to store in that variable.

For example, you might store a number, a date, or a string of text. You tell Excel what type of data is going to be stored in the variable before you start using it.

Let’s take a look at an example in VBA. We’re going to create a variable called “firstName” and tell Excel that it will contain a string of text. Here’s the syntax we’ll use:

Sub getNames()
Dim firstName As String
End Sub

Let’s go over that one step at a time.

“Dim firstName As String.”

Dim is short for “Dimension,” and it’s what you use to declare a new variable. The dim statement tells Excel that the next thing we type is the variable name. In this case, that’s “firstName.”

After that, we have “As.” You always need “As” in your declaration statement—it tells Excel that you’re going to use the following VBA data type for that variable.

And then “String” is the actual VBA data type you want.

So in our case, we’re saying “I’m going to use a variable called firstName, and it’s going to contain Strings.”

So, why declare variables?

Alright, so now you know how to declare VBA variables and how it’s done.

But why? It seems like extra work just as a courtesy to Excel 😆

You need to declare variables because if you don’t, Excel will do it for you (invisibly). And Excel always declares any variable as the “Variant” variable type.

In most cases, that’s not a problem at all.

But when your code gets too dense, and when you use the variables “too much”, it might become a problem because the “Variant” data type hold any type of data.

Kasper Langmann, Microsoft Office Specialist

That also makes it very heavy on your computer because it takes up much more space than other VBA data types. It gets a bit technical now but I’ll try and keep it short ⚙️

For most, it’s sufficient to know that any VBA data type you declare will take up much less space than the default Variant variable type, thus reducing the workload on your computer tremendously.

PRO TIP

VBA variable declaration actually helps you debug your code before you run into potential problems, no matter what data types you use.

If you try to put a value into a variable it’s not declared to contain, Excel shows an error message.

So, you can’t put the text “Spreadsheeto” into an Integer VBA variable, for example.

Setting a VBA variable

In many programming languages, you can assign a value to the variable in the same statement that you use to declare it.

In VBA, declaring VBA variables is optional, but you can’t declare AND set the variable at the same time.

Instead, you’ll need to create a new line that assigns a value. Let’s take a look at an example:

Sub getNames()
 Dim firstName As String
 firstName.Value = "Jason"
End Sub

We’ve added a line that assigns the value of a variable. In VBA, just append “.Value”, an equals sign, and the value you want to assign (in quotation marks).

Here’s another example of a different VBA data type declaration:

Sub calculateSales()
 Dim averageSales As Long
 averageSales.Value = "43000"
End Sub

In this one, we’re telling Excel that averageSales will contain numbers because the Long datatype is for storing large numbers. Also, that the averageSales declared variable should have an initial value of 43,000.

Remember that variables can change, so we’re only assigning an initial value here.

Kasper Langmann, Microsoft Office Specialist

You can also assign a value to a variable without the .Value method. You can just use a line like this:

However, it’s generally a good idea to be as specific as possible when programming. And because it’s easy to type “.Value”, there’s no reason not to.

Common VBA data types

Now that you understand how to declare and assign values to an object variable in VBA, let’s talk about VBA data types.

This is a basic introduction to VBA data types. For most VBA beginners, this will be all you need to know. If you need more information, though, like byte counts or user-defined structures, check out Microsoft’s data type summary.

Kasper Langmann, Microsoft Office Specialist

To start, let’s just look at a quick comparison of some of the numerical VBA data types.

Integer can hold 2 bytes of data – but only numbers. That means it can hold both positive values and negative values, in whole numbers between -32,768 and 32,767.

Long can hold 4 bytes. Again, only whole numbers (both positive values and negative values) but this time between -2,147,483,648 and 2,147,483,647

Double holds 8 bytes, but includes decimals!

Something worth noting: the double data type only stores an approximation of long numbers. This makes it good for storing very large numbers but can cause some issues with complex calculations.

Kasper Langmann, Microsoft Office Specialist

Keep in mind that Integer will always round your decimals to the nearest integer, which means you might get some strange results if you’re not expecting them. If you need more precision, use Double.

There are many other numerical VBA data types. But you should be able to handle just about any case with the 3 above.

What about non-numerical types? There are two common ones: String and Boolean.

String is simple—it holds text. Excel won’t be able to run calculations on Strings (though it will be able to use some text functions).

Boolean holds true and false values; you could use 0 or 1 in a numerical data type, but you can save computational power and be more accurate in your data assignments if you use a Boolean variable.

That’s it – Now what?

If you plan on using VBA to create macros, you’re going to want to get used to working with variables. You’ll be using them a lot.

If you’re starting out with VBA, don’t worry too much about optimizing for the best data types in your VBA dim statement. If you know that Integer rounds to whole numbers and Double is for both big numbers and precision, you’ve made a good start.

Also, if you’re starting out learning VBA, you don’t want to miss my free 30-minute Excel VBA course. Click here to enroll.

Other resources

As mentioned before, if you need some of the more niche variable types for your declarations, check out Microsoft’s exhaustive list here. This list also shows the actual size taken up by the data type.

The list actually applies to the Visual Basic programming language – but because VBA is a derivative of Visual Basic, it also applies to VBA.

You can also check out my extensive guide to VBA programming here.

If you want to learn how to declare variables in a hard (but effective) way, you can force the VBA editor to require you to declare all variables you use. with something called the Option explicit statement. Read about the Option explicit statement here.

Frequently asked questions

You declare it by using the Dim statement like this:

“Dim variableA as String”

Put that at the start of your macro to declare the “variableA” variable as a String, so it can contain text.

Dim means dimension and you use the VBA dim statement to declare a variable, telling Excel what data it will contain. This is useful for optimizing your VBA code.

Kasper Langmann2023-01-30T19:45:11+00:00

Page load link

VBA Dim

Excel VBA Dim

DIM in VBA can be termed as it declares variable in different data types such as integer Boolean string or double etc. In any programming language, a variable needs to be declared to a specific data type such as X is a variable and if we define X as an integer which means we can store integer values in X. Now if we declare Y as a string it means we can store string values in Y.

As discussed above DIM in VBA is used to declare variables of different data types. But what is DIM in VBA? DIM means dimension or Declare in Memory in VBA. We declare a variable to a specific data type in VBA we use the DIM keyword to do it. We can use the classes structures already inbuilt in VBA or we can create a new one ourselves. To give a very basic explanation on DIM we can take this as an example, for instance, we need to store logical values in a variable. Logical values mean either they are true or they are false. Now logical values are Boolean in data types as we know, so we need to declare our variable in Boolean data type.

If we say X variable has to store the value in Boolean we need to declare X as a Boolean variable so that it can store the data type we want to.

Use of DIM with syntax in VBA is as follows:

DIM Variable As DataType.

When we try to define a specific data type excel pre types it for us.

Have a look at the screenshot below,

Sample

Excel determines from the keywords we type and displays the possible data types we might want to use.

How to Use VBA Dim in Excel?

We will learn how to use VBA Dim with a few examples in excel.

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

Excel VBA Dim – Example #1

First, let us use Integer as the data type to declare. We will use three variables and declare each of them as integers using DIM keyword. And then we will display the final output.

Tip: To use VBA in excel we need to have developer access enabled from the accounts option in the file tab.

Step 1: Go to the Developer tab and click on Visual Basic to open VBA Editor.

Example 1-1

Step 2: In the project window click on sheet 1 to open the code window.

VBA Dim Example 1-2

Step 3: When the code window opens up to declare the sub-function to start writing the code.

Code:

Sub Sample()

End Sub

VBA Dim Example 1-3

Step 4: Declare three variables A, B and C as integers.

Code:

Sub Sample()

Dim A As Integer
Dim B As Integer
Dim C As Integer

End Sub

VBA Dim Example 1-4

Step 5: Assign those three variables any random values.

Code:

Sub Sample()

Dim A As Integer
Dim B As Integer
Dim C As Integer
A = 5
B = 10
C = A + B

End Sub

VBA Dim Example 1-5

Step 6: Display the values of C using the msgbox function.

Code:

Sub Sample()

Dim A As Integer
Dim B As Integer
Dim C As Integer
A = 5
B = 10
C = A + B
MsgBox C

End Sub

VBA Dim Example 1-6

Step 7: Run the code from the run button, Once we run the code we get the following result as the output.

Result of Example 1-1

Step 8: As A, B and C were declared as integer and the sum of A and B is also an integer the value stored in C can be displayed. But if we change the value of C = A / B as shown in the screenshot below.

VBA Dim Example 1-8

Step 9: Now let us run the code again and see what we get as the result,

Result of Example 1-2

We get zero as the result but 5 /10 is 0.5, not 0. It is because C can store only integer values not the values after the decimal.

Excel VBA Dim – Example #2

In the previous example, we saw that if the value of the result in C is in decimals the values after the decimals are not displayed in the output because we declared C as an integer. Now we will use a different data type to declare from DIM function to display the original value of C.

Step 1: Go to the Developer’s tab and click on Visual Basic to open VBA Editor.

VBA Dim Example 1-1

Step 2: In the project window click on Sheet 2 to open the code window.

VBA Dim Example 2-2

Step 3: Once the code window is open, create a sub-function to start writing the code.

Code:

Sub Sample1()

End Sub

VBA Dim Example 2-3

Step 4: Declare three variables A B and C. Declare A and B as integers while C as double.

Code:

Sub Sample1()

Dim A As Integer
Dim B As Integer
Dim C As Double

End Sub

VBA Dim Example 2-4

Step 5: Similar to example 1 assign the values to these variables.

Code:

Sub Sample1()

Dim A As Integer
Dim B As Integer
Dim C As Double
A = 5
B = 10
C = A / B

End Sub

VBA Dim Example 2-5

Step 6: Now Display the output using the msgbox function.

Code:

Sub Sample1()

Dim A As Integer
Dim B As Integer
Dim C As Double
A = 5
B = 10
C = A / B
MsgBox C

End Sub

VBA Dim Example 2-6

Step 7: Run the code from the run button. Once we run the code we get the following result,

Result of Example 2

Now we have the exact value of C which is 0.5.

Excel VBA Dim – Example #3

Let us use a DIM function to store characters means strings.

Step 1: Go to the Developer’s tab and click on Visual Basic to open VBA Editor.

Example 3

Step 2: In the project window click on Sheet 3 to open the code window.

VBA Dim Example 3-2

Step 3: Create a sub-function to start writing the code,

Code:

Sub Sample2()

End Sub

VBA Dim Example 3-3

Step 4: Declare a variable A as a string,

Code:

Sub Sample2()

Dim A As String

End Sub

VBA Dim Example 3-4

Step 5: Assign any random values to A,

Code:

Sub Sample2()

Dim A As String

A = "Anand"

End Sub

VBA Dim Example 3-5

Step 6: Display the output using the msgbox function.

Code:

Sub Sample2()

Dim A As String

A = "Anand"

MsgBox A

End Sub

VBA Dim Example 3-6

Step 7: Run the code from the run button provided and see the result,

Result of Example 3

Explanation of VBA DIM

DIM in VBA is used to declare variables as different data types. The variables can be a single variable or an array which we need to keep in mind to declare a proper data type in order to get proper output.

For example, if our output is going to be in String we need to declare the variable in String and if the output is going to be in decimals then declare the variable as double etc.

Things to Remember

There are a few things we need to remember about DIM in VBA:

  • Excel pre-types the data type while using the dim function using the keystrokes we use.
  • For specific data outputs, proper data types must be declared to get the desired result.
  • A dim function is used to declare a single variable or an array.

Recommended Articles

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

  1. VBA TIMER
  2. VBA Color Index
  3. VBA MsgBox
  4. VBA Select Case

Понравилась статья? Поделить с друзьями:
  • Vba delete table excel
  • Vba delete row from excel
  • Vba date picker excel
  • Vba copy row excel vba
  • Vba copy formatting excel