Excel vba для чего option explicit

Хитрости »

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


Option Explicit — начинающие программировать в Visual Basic могут увидеть данную строку в чужом коде, либо случайно в своем. Хотя кто-то может быть уже знает, что это и зачем и использует данное объявление намеренно. Я же постараюсь максимально подробно описать смысл этой строки и её полезность для кода в первую очередь для тех, кто еще не знает для чего она.

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

Собственно что же делает эта строка? А делает она следующее: она принуждает Вас объявлять переменные(если не знаете смысл объявления переменных — читайте здесь). Если какая-либо переменная внутри выполняемой процедуры не объявлена — Вы увидите такое вот сообщение:

рис.1

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

  • во-первых: объявление переменных считается хорошим тоном при программировании
  • во-вторых: правильное присвоение типов недурно экономит память
  • ну и в-третьих(я бы даже сказал в главных): это помогает избежать неявных ошибок кода при несовпадении типов данных

А теперь перейдем к сути и попробуем разобраться в чем же польза от использования Option Explicit. Ниже приведен простой код:

Sub Check_Variables()
    Dim a As String
    a = "Привет от www.excel-vba.ru"
    MsgBox а, vbInformation
End Sub

Выполните данный код без строки Option Explicit. Какое значение выдаст MsgBox? Ничего. Что за странность? Ведь явно видно, что переменной присвоено значение текста. Ничего больше не происходит. Но переменная все равно пуста. Мистика…А теперь запишите первой строкой в модуле Option Explicit:

Option Explicit
Sub Check_Variables()
    Dim a As String
    a = "Привет от www.excel-vba.ru"
    MsgBox а, vbInformation
End Sub

Запустите код. И что же видите? Видите сообщение, показанное на рис.1 и выделенную переменную «а», в последней строке. Что это означает? Это означает, что переменная «а» у нас не объявлена. А все потому, что первой строкой (Dim a As String) я объявил переменную на английском языке, а в последней строке я записал её на русском. А для кода это разные символы. Если разглядеть логику работы VBA — первую «а» он видит как переменную с присвоенным типом String. И ей мы задаем значение «Привет от www.excel-vba.ru». А вторую…Вторую он не находит в объявленных переменных, не находит в функциях и сам инициализирует её как новую переменную с типом данных Variant. И, что вполне логично, со значением Empty, т.е. ничего, т.к. этой переменной мы никаких значений не присваивали.

Еще один классический пример, когда Option Explicit спасет от лишних мозговых штурмов. Имеем простую функцию пользователя(UDF), которая берет указанную дату и возвращает её в заранее заданном формате в текстовом виде:

Function GetDateAsText(Optional ByVal Дата As Date)
    If Дата = 0 Then
        Дата = Date
    End If
    GetDataAsText = Format(Дата, "DD MMMM YYYY")
End Function

Хоть функция и короткая, но даже в ней не сразу порой бросается в глаза опечатка(представим, если функция в реальности строк на 200). В итоге чаще всего автор функции не понимает, почему при записи её на листе она возвращает не дату вида «21 мая 2016», а 0 и начинает пошагово выполнять функцию, искать ошибки в логике кода и т.д. Но если поставить в начало модуля Option Explicit, то при первом же выполнении этой функции VBA подсветит нам «GetDataAsText = «, указывая тем самым, что GetDataAsText в чем-то отличается от заданного имени функции — GetDateAsText. Банальная опечатка: GetDataAsText — GetDateAsText.


А теперь представьте себе, что Вы написали кучу длинного кода, строк на 100 или более. Конечно, Option Explicit Вы не используете. И вот Вы тестируете код, но он работает как-то не так…Где-то что-то неверно выполняется. И Вы начинаете пошагово ковыряться в листинге и искать ошибку…А ведь все может быть и проще: где-то в коде Вы могли банально опечататься и присвоить таким образом значение переменной, на которую Вы и не рассчитывали. А если использовать Option Explicit, то такая опечатка будет сразу обнаружена еще до выполнения кода и, что немаловажно — подсвечена. Так что Вам даже не придется её искать, а останется лишь исправить ошибку.

Так же эта строка поможет избежать неявных ошибок и в других ситуациях. В частности, при обращении к другим приложениями(Word, Outlook и т.д.). Например, в Excel применяются именованные константы для многих задач. Одна из распространенных — поиск последней ячейки в столбце: llast = Cells(Rows.Count, 1).End(xlUp).Row
здесь xlUp является именованной константой, значение которой равно числу: -4162. В других приложениях такой же подход. Это избавляет от необходимости помнить на память все значения констант и обращаться к ним при помощи intellisense. Но действуют эти константы исключительно внутри своего приложения(можете обратить внимание, у Excel константы начинаются с xl, а у Word — с wd). И т.к. объявлены эти константы в других приложениях — Excel про них не знает(как и другие приложения не знают про константы Excel). Для примера возьмем простой и рабочий код замены в Word:

    Dim wdDoc As Object
    Set wdDoc = objWordApp.ActiveDocument
    With wdDoc.Range.Find
        .Text = "привет"
        .Replacement.Text = "привет"
        .wrap = wdFindContinue
        .Execute Replace:=wdReplaceAll
    End With

Где wdFindContinue для Word-а равно 1, а wdReplaceAll = 2. Но это происходит только при выполнении изнутри самого Word-а(или при раннем связывании через ToolsReferences. Подробнее про это можно почитать в статье: Как из Excel обратиться к другому приложению).

Если же скопировать и выполнять данный код из Excel, то работать он будет не так как задумали. Дело в том, что Вы считаете, что Excel работает с обозначенными константами(wdFindContinue, wdReplaceAll) наравне с Word-ом. Но Excel на самом деле про них ничего не знает. И если директива Option Explicit будет отключена, то Excel просто назначает им значение по умолчанию — Empty. Которое преобразуется в 0. А это совсем иной поиск получается, т.к. должны быть значения 1 и 2. А если бы Option Explicit была включена, то Excel выделил бы их и указал, что они не объявлены. И тогда можно было бы сделать либо так:

    Dim wdDoc As Object
    Const wdFindContinue As Long = 1
    Const wdReplaceAll As Long = 2
    Set wdDoc = objWordApp.ActiveDocument
    With wdDoc.Range.Find
        .Text = "привет"
        .Replacement.Text = "привет"
        .wrap = wdFindContinue
        .Execute Replace:=wdReplaceAll
    End With

либо так(что удобнее, на мой взгляд):

    Dim wdDoc As Object
    Set wdDoc = objWordApp.ActiveDocument
    With wdDoc.Range.Find
        .Text = "привет"
        .Replacement.Text = "привет"
        .wrap = 1
        .Execute Replace:=2
    End With

Так что думаю, не стоит недооценивать значимость строки Option Explicit при написании кодов. В довершение хотелось бы Вас обрадовать, что вписывание данной строки в начало каждого модуля можно сделать автоматическим: поставить в опциях редактора галочку: ToolsOptions-вкладка EditorRequire Variable Declaration. Теперь во всех новых созданных модулях строка Option Explicit будет создаваться самим редактором VBA автоматически. К сожалению, в уже имеющихся модулях Вам придется проставить данную строку самим вручную. Но это того стоит, поверьте.

Так же см.:
Что такое переменная и как правильно её объявить?


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

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


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



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

Справочная таблица по встроенным типам данных VBA Excel. Функция TypeName, возвращающая тип данных переменной. Оператор Option Explicit в начале модуля.

Встроенные типы данных

Встроенные типы данных VBA Excel:

Тип данных Байты* Диапазон значений
Byte 1 Целые числа:
от 0 до 255
Boolean 2 True (Истина) или False (Ложь)
Integer 2 Целые числа:
от -32768 до 32767
Long 4 Целые числа:
от -2147483648 до 2147483647
Single 4 Отрицательные числа:
от -3,402823Е+38 до -1,401298Е-45
Положительные числа:
от 1,401298Е-45 до 3,402823Е+38
Double 8 Отрицательные числа:
от -1,79769313486232Е+308
до -4,94065645841247Е-324
Положительные числа:
от 4,94065645841247Е-324
до 1,79769313486232Е+308
Currency 8 от -922337203685477,5808
до 922337203685477,5807
Date 8 с 1 января 100 года
по 31 декабря 9999 года
Object 4 Ссылка на объект
String
(переменной длины)
10 + длина строки от 0 до ≈2 млрд символов
String
(фиксированной длины)
длина строки от 1 до ≈65400 символов
Variant
(числа)
16 В пределах диапазона типа
данных Double
Variant
(символы)
22 + длина строки от 0 до ≈2 млрд символов

Дополнительно для VBA7:

Тип данных Байты* Диапазон значений
LongLong 8 Целые числа:
от –9 223 372 036 854 775 808
до 9 223 372 036 854 775 807
Доступен только в 64-разрядных системах.
LongPtr 4 или 8 В 32-разрядных системах соответствует типу Long:
от -2147483648 до 2147483647,
в 64-разрядных — типу LongLong:
от –9 223 372 036 854 775 808
до 9 223 372 036 854 775 807

*Резервируется память в байтах на каждую переменную соответствующего типа.

Тип данных Variant может принимать специальные значения: Empty, Error, Nothing и Null.

Кроме встроенных типов данных VBA Excel позволяет использовать пользовательские типы, создаваемые с помощью оператора Type. Диапазон значений пользовательского типа данных определяется встроенными типами, из которых он состоит.

Переменные с типами данных Byte, Boolean, Integer, Long, Single и Double можно объявлять с помощью суффиксов.

Функция TypeName

TypeName – это функция, возвращающая значение типа String с информацией о переменной.

Чаще всего, функция TypeName возвращает наименование типа данных аргумента (значения), содержащегося в переменной. Кроме наименований встроенных типов данных, функция TypeName может возвращать следующие значения:

Значение Описание
Collection, Dictionary, Range, Worksheet и т.д. Тип известного объекта, ссылка на который содержится в объектной переменной
Error Переменная содержит значение ошибки
Empty Неинициализированное значение
Null Отсутствие допустимых данных
Unknown Объект, тип которого неизвестен
Nothing Объектная переменная, которая не ссылается на объект

Если переменная объявлена с числовым типом данных или String, функция TypeName возвратит наименование этого типа данных. Если переменная объявлена с типом данных Variant или Object, возвращаемое значение будет зависеть от содержимого переменной.

Пример:

Sub Primer()

Dim a As Single, b As Date, c As Variant

    MsgBox «a As Single:  « & TypeName(a)  ‘Single

    MsgBox «b As Date:  « & TypeName(b)  ‘Date

    MsgBox «c As Variant:  « & TypeName(c)  ‘Empty (значение не инициализировано)

c = 1.236

    MsgBox «c = 1.236:  « & TypeName(c)  ‘Double

Set c = Cells(1, 1)

    MsgBox «Set c = Cells(1, 1):  « & TypeName(c)  ‘Range (тип объекта)

Set c = Worksheets(1)

    MsgBox «Set c = Worksheets(1):  « & TypeName(c)  ‘Worksheet (тип объекта)

End Sub

Оператор Option Explicit

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

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

Чтобы избежать ошибок при работе с переменными используется оператор Option Explicit. Он указывает на то, что все переменные в модуле должны быть объявлены с помощью ключевого слова Dim или ReDim. В этом случае, если компилятор обнаружит строку с необъявленной переменной, то сгенерирует ошибку и выделит эту переменную.

Размещается оператор Option Explicit в самом начале модуля перед всеми остальными операторами. Чтобы каждый раз не вставлять его вручную и, тем более, не забыть о нем, можно настроить редактор VBA Excel, чтобы он автоматически добавлял Option Explicit при создании нового модуля.

Настройка автоматического добавления Option Explicit

1. Откройте окно Options через вкладку меню Tools:

Путь к окну Options

2. Отметьте галочкой опцию Require Variable Declaration на вкладке Editor:

Окно Options

3. Теперь новый модуль открывается со строкой Option Explicit:

Строка Option Explicit вставлена


Home / VBA / How to use Option Explicit Statement in VBA

KEY POINTS

  • Option Explicit forces you to declare all the variables.
  • It’s a statement that you can use at the start of a module.
  • You can enter it manually or activate it from the options.
  • You need to use Option Explicit only once.
  • It also helps you to identify typing errors while using variables.

What is VBA Option Explicit

Option Explicit is a statement that you can use at the beginning of a module to force yourself to declare all the variables. When you add this statement, VBA shows you a compile error when you execute the code and also highlights the variable in the code that you need to declare.

When you add an option explicit at the beginning of a module, VBA adds a separator line below it, and then you can start writing a procedure. And when you have the option explicit statement, and you run a procedure, VBA checks if there is a variable that is not declared and shows you an error message.

Option Explicit
Sub myMacro()
a = 50
MsgBox a
End Sub   

Above is the message that you get when a variable is not declared.

Activate Option Explicit in VBA

To activate the option explicit statement in a module, use the following steps.

  1. First, open the Visual Basic Editor and in the tools menu click on the options.
    3-activate-option-explicit-in-vba
  2. After that, in the options in, go to the editor tab and tick mark “Require Variable Declaration”.
    4-editor-tab-and-tick-mark
  3. In the end, click OK.
  4. Once you do that, VBA will add option explicit whenever you add a new module.

But it doesn’t add this statement to your existing module, so you need to add them manually to each of the existing modules one by one.

How to Add it Manually?

As I mentioned the Option Explicit statement must go before the first procedure in the module (Sub or Function). So, you need to add this statement above the first procedure (General Declarations area) and make sure to add it only once.

If you add it within a procedure, or between two procedures, VBA will show you an error when you try to execute any of the code in the module.

Examples (Why using Option Explicit Statement is a Good Habit)

Let me show you an example to make you understand why the Option Explicit statement is highly recommended to use. Look at the following code.

Sub myMacro()
  Dim myText As String    
  myText = "Puneet"    
  MsgBox   MyTxt    
End Sub

In this code, I have declared a variable “myText” as a string and then defined the value of this variable. And in the end, I used a message box that shows the value of the variable, but if you look carefully I have miss-spelled that variable as “MyTxt” instead of “myText”.

Now when I run this code, it shows me a blank message box.

I need your 2 minutes to help you understand the real problem here.

When I mistyped the variable name, VBA takes it as a separate variable, and as I am not using the option explicit statement, it doesn’t show me an error.

That is why the message box uses the second variable (mistyped) which has no value assigned to it. Now think for a second; if you are writing a lengthy code and not using option explicit statement, it will be hard for you to trace down this error until you reread the entire code.

But with the option explicit statement ON, when I run this code, it shows an error.

Option Explicit
Sub myMacro()
Dim myText As String 
myText = "Puneet" 
MsgBox MyTxt 
End Sub

We strongly recommend to use Option Explicit at the start of your Excel VBA code. Using Option Explicit forces you to declare all your variables.

For example, place a command button on your worksheet and add the following code lines:

Dim myVar As Integer
myVar = 10
Range(«A1»).Value = mVar

Result when you click the command button on the sheet:

Without Option Explicit in Excel VBA

Clearly, cell A1 does not contain the value 10. That is because we accidentally misspelled myVar. As a result, Excel VBA places the value of the undeclared, empty variable mVar into cell A1.

When using Option Explicit, the code lines above generate an error because we did not declare the variable mVar.

Use Option Explicit

Result:

Variable not Defined

1. Click OK. Then Click on Reset (Stop) to stop the debugger.

2. Correct mVar so that it reads myVar.

Result when you click the command button on the sheet:

With Option Explicit in Excel VBA

Now you know why you should always use Option Explicit at the start of your Excel VBA code. It avoids incorrectly typing the name of an existing variable.

Fortunately, you can instruct Excel VBA to automatically add Option Explicit.

1. In the Visual Basic Editor, click on Tools and then click on Options.

2. Check Require Variable Declaration.

Require Variable Declaration

Note: Option Explicit will not be added automatically to existing Excel files. Simply type in Option Explicit yourself if you want to use it.

Информация о материале
Категория: Основы VBA

Опубликовано: 08 октября 2012

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

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

Для того чтобы установить режим Option Explicit, при котором VBA требует явного объявления всех переменных в модуле, необходимо добавить команду Option Explicit в начало модуля, перед любыми объявлениями переменных.

Option Explicit   'требование явного объявления переменных в модуле
Dim HelloMsg      'переменная будет использоваться всеми процедурами модуля
Sub HelloWorld()
    HelloMsg="Hello, World!"
    MsgBox HelloMsg,, "Окно приветствия"
End Sub

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

Редактором Visual Basic предусмотрена возможность автоматически включать Option Explicit в каждый новый модуль при его создании. Для этого необходимо в редакторе VB зайти в меню Tools/Options  и в диалоговом окне «Options» на вкладке «Editor» поставить флажок перед опцией Require Variable Declaration (явное описание переменных).

как добавить Option Explicit во все новые модули VBA

Другие материалы по теме:

vba option explicit

The Excel VBA Option Explicit statement is such useful feature in Excel VBA, it is strange, this is the first time I am writing a post about it. It proves incredibly useful in preventing typos and other stupid mistakes when developing Visual Basic for Applications macros. But what does it actually do?

What does Option Explicit do?

The VBA Option Explicit statement can either:

  • Forces an explicit declaration of all variables in a VBA Module
  • Allow the implicit declaration of variables in VBA Modules

However, the first question most people have is…

What is explicit and implicit variable declaration?

Explicit variable declaration in VBA is the declaration of a variable with the use of the VBA Dim statement:

Dim x as Long 'Explicit declaration
x = 1

Implicit variable declaration on the other hand is the opposite – the usage of a variable without any preceding declaration. The VBA Compiler will create a variable that has been used even if it was not preceded with an explicit declaration:

x = 1 'Implicit declaration

Now that we know what implicit and explicit declarations we can ponder on a second on why we would want to force explicit variable declaration. Well, for a number of reasons:

  • To prevent variable name typos
  • Clean up VBA Code
  • Optimize VBA performance

By default all implicit variables are Variant types. Variants are much less efficient than other data types (Longs, Integers, Strings etc.). Read more on VBA Performance here

Using Option Explicit

Option Explicit 'Declare that all variables are to be explicitly declared

Sub Main
 Dim x as Long
 x = 1 'OK!
 y = 10 'ERROR!
End Sub

option explicit errorWhat happens when you try to declare a variable implicitly. Believe me, it is better to fix Variable not defined errors than scramble to find variable name typos.

Turn on Option Explicit by default

For me the Option Explicit statement is a must requirement. I turn it on by default in all my macros. Even when using Variant variables.

turn on option explicitHow to turn on Option Explicit by default for all VBA Code Modules? Go to Tools->Options.... In the Options window select Require variable declaration. That is it! Similarly you can turn off the addition of the Option Explicit statement in all your VBA Code Modules by unchecking this option.

Declaration of variables is very important in VBA. Option Explicit makes a user mandatory to declare all the variables before using them. Any undefined variable will throw an error while executing the code. We can write the keyword option explicit or enable it for all codes from options by enabling variable declaration.

In VBA, it is all about variables. To store data, we need variables with a suitable data type. You can question us why you need variables when you can directly add the value to the spreadsheet itself. It is mainly because of the multiple users of the workbook. If one person handles it, you can directly reference the value to the sheet. Therefore, we can make a flexible code to store the data by declaring variables.

Table of contents
  • Excel VBA Option Explicit
    • What is VBA Option Explicit?
    • How to Make the Variable Declaration Mandatory?
    • Option Explicit is your Saver
    • Recommended Articles

What is VBA Option Explicit?

We hope you have come across the blue-lined word “Option Explicit” at the top of your module before any Macro starts in that module.

option explicit 1

At the start of learning VBA, we also didn’t understand what that was, and to be very frank, we didn’t even think about this. So not only for you or me, but it is also the same for everybody at the start. But we will see the importance of this word now.

“Option Explicit” is our mentor in declaring the variable. By adding this word, it makes the variable declaration a mandatory process.

You can download this VBA Option Explicit Excel Template here – VBA Option Explicit Excel Template

For example, look at the below code for understanding.

Code:

Sub Example1()

     i = 25

     MsgBox i

End Sub

option explicit example 1

If we run this code, we will get the variable “I” value in the message box in VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.

option explicit example 1.1

Now, we will add the word “Option Explicit” at the beginning of the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.

option explicit example 1.3

Now, we will run the code and see what happens. If you practice with us, press the F5 key to run the code.

option explicit example 1.4

We got a compile error, saying, “Variable not defined.” That is why we have not declared the variable “i,” but straight away, we have assigned the value to it as 25.

Since we have added the word “Option Explicit,” it forces us to declare the variable compulsorily.

In the above code, the alphabet “i” is undeclared, so we have added the variable controller word “Option Explicit” which prevents us from using the undeclared variables.

The moment you add the word “Option Explicit” at the top of the module, it is applicable for all the macros in that particular module to declare the variables mandatorily.

How to Make the Variable Declaration Mandatory?

If you have manually added the variable mentor “Option Explicit” in your module when you insert the new module, you will not get this variable mentor by default.

option explicit example 2.5

option explicit example 2.4

If you think every time you need to add the word “Option Explicit” for all the new modules manually, then you are wrong.

Because we can make this word mandatory in all the modules by doing a simple setting, follow the below steps to adjust the settings.

  1. Go to Visual basic editor.
  2. Go to TOOLS and click on “Options.”

    option explicit example 2.1

  3. When you click “Options,” you will see the window below.

    option explicit example 2.2

  4. Under this window, go to “Editor” and tick the option “Require Variable Declaration.”

    option explicit example 2.3

  5. Click on “OK” to close the window.

    Whenever you add a new module, it automatically inserts the word “Option Explicit” by default.

    option explicit example 2.6

Option Explicit is your Saver

Option Explicit helps us in many ways. Making the declaration of variables mandatory will help us until the execution. Look at the below code.

Code:

Sub Example2()
Dim CurrentValue As Integer

CurentValue = 500

MsgBox CurrentValue

End Sub

example 3.1

We have declared the variable “CurrentValue” in the above code as an integer. In the next line, we have assigned the value of 500 to it. So, if we run this code, we should get 500 because of a message box. But see what happens.

example 3.3

It says “Variable not defined” and highlights the second line.

If we closely look at the second line, there is a slight spelling mistake. My variable name is “CurrentValue,” but in the second line, we have missed out on one spelling, i.e., “r.” So, it says “CurrentValue” instead of “CurrentValue.” Since we have made the variable declaration mandatory by adding the word “Option Explicit” in Excel VBA, it has highlighted the typo error we have made.

So, when we correct the spelling and run the code, we will get the result as follows.

example 3.2

Say hello to the newly appointed variable mentor!

Recommended Articles

This article has been a guide to VBA Option Explicit. Here, we discuss the Option Explicit in VBA and how to make variable declaration mandatory with details. You can learn more about VBA from the following articles: –

  • VBA Wait Function
  • VBA TimeValue
  • Class Modules in VBA
  • Call Sub in VBA

Return to VBA Code Examples

Declaring Option Explicit at the top of your code module tells VBA to require that you declare all the variables which you are using in the code. If this command is omitted, you can use variables which you haven’t declared. We recommend using the Option Explicit at the top of your module, as it helps you to avoid mistyping of the variables.

Using VBA Variables without Option Explicit

We will first show the example of the code when there is no Option Explicit command. Here is the code:

Private Sub ExampleWOOptionExplicit()

    Dim strTextA As String

    strTextA = "Testing VBA without Option Explicit"

    MsgBox strTextA

End Sub

In the example, we declared the variable strTextA in the first row of the procedure and assigned it the text. After that, we want to return the message box with the value of strTextA. Here is the result when we run the code:

vba-without-option-explicit

Image 1. The code without Option Explicit

As you can see in Image 1, the code is successfully executed. The message box with the value from strTextA appeared, even though we didn’t declare variable strTextA.  Here there is no problem with the code, but what if we had misspelled the variable name:

MsgBox strTxtA

Here we wrote strTxtA (without an “e”) instead of strTextA. As a result we get a blank message box, because the variable strTxtA was not defined. Now we will see how to use Option Explicit to prevent errors.

Using the Variables with Option Explicit

If you want to prevent using variables that are not declared, you have to enter Option Explicit at the top of your module:

Option Explicit

Here is the complete code, including the typo:

Option Explicit
Private Sub ExampleWithOptionExplicit()

    Dim strTextA As String

    strTextA = "Testing VBA without Option Explicit"   

    MsgBox strTxtA

End Sub

Let’s see what happens if we run the code:

Image 2. The code with Option Explicit

As a result, we get the error “Variable not defined”, because we didn’t declare the strTxtA variable.

Adding Option Explicit at the top of your code modules helps prevent errors from misspelled variables.

If you want to learn more about VBA other VBA options, learn about how to make VBA case-insensitive: Prevent VBA Case Sensitive

VBA Coding Made Easy

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

Learn More!

Понравилась статья? Поделить с друзьями:
  • Excel vba длина ячейки
  • Excel vba есть ли формула
  • Excel vba длина текста в ячейке
  • Excel vba есть ли такой лист
  • Excel vba длина string