Excel vba global objects

Содержание

  1. VBA Global Variable
  2. Procedure-level Variable
  3. Module Level Variable
  4. Global Level Variable
  5. VBA Coding Made Easy
  6. VBA Code Examples Add-in
  7. VBA Global Variables — Как объявить глобальные переменные в Excel VBA?
  8. Глобальные переменные Excel VBA
  9. Как объявить глобальные переменные в VBA?
  10. VBA Global Variables — Пример № 1
  11. VBA Global Variables — Пример № 2
  12. Плюсы VBA Global Variable
  13. Минусы VBA Global Variable
  14. То, что нужно запомнить
  15. Рекомендуемые статьи
  16. VBA Global Variables
  17. Excel VBA Global Variables
  18. How to Declare Global Variables in VBA?
  19. VBA Global Variables – Example #1
  20. VBA Global Variables – Example #2
  21. Pros of VBA Global Variable
  22. Cons of VBA Global Variable
  23. Things to Remember
  24. Recommended Articles

VBA Global Variable

In this Article

In this tutorial we will cover VBA Global Variables.

In VBA, variables can be declared with different scopes. The scope determines where the variable can be used.

Procedure-level Variable

Typically, you will see variables declared at the procedure-level within Sub Procedures or Functions. Procedure-level variables must be declared using the Dim keyword within the procedure where they will be used.

This example declares someNumber as an integer variable within the procedure.

You can only use this variable within this Sub Procedure. If you call the variable from another Sub Procedure you would get the following Compile Error:

Module Level Variable

A Module-level variable can be used by any Sub Procedure or Function within that module. You need to place the variable declaration at the top of the module in the Declarations section, under the Option Explicit statement, and use the Dim keyword:

Now the variable someNumber can be used in both sub procedures.

Global Level Variable

A global-level variable can be used anywhere within your code, within Modules, Functions, Sub Procedures and Classes. Global variables are declared in the Declarations Section, under the Options Explicit statement and using the keyword Global. The way you declare a Global level variable is shown below. Both of the Sub Procedures in Module1 can use this variable.

Since this variable is a Global level variable, you can also use it in Module2:

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 Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

VBA Global Variables — Как объявить глобальные переменные в Excel VBA?

Глобальные переменные Excel VBA

Мы обычно объявляем любую переменную, используя слово DIM, и это лучший прямой способ сделать это. Но переменные, объявленные с использованием DIM, могут использоваться только в одном модуле. Если мы попытаемся использовать эту переменную, определенную с помощью DIM, она будет применима для модуля, в котором она объявлена. Что если мы хотим использовать переменную в любом модуле или проекте? Что не может быть возможным, если мы продолжаем использовать DIM для определения этой переменной?

В этом случае у нас есть вторичная опция, определяющая переменную по слову Global или Public в VBA. Глобальные или публичные переменные VBA — это те переменные, которые объявлены в начале подкатегории с помощью Option Explicit. Что бы мы ни делали или не могли делать в подкатегориях, они выполняются до этого в Option Explicit.

Как объявить глобальные переменные в VBA?

Ниже приведены различные примеры объявления глобальной переменной в Excel с использованием кода VBA.

Вы можете скачать этот шаблон Excel для глобальных переменных VBA здесь — Шаблон Excel для глобальных переменных VBA

VBA Global Variables — Пример № 1

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

  • Перейдите в меню « Вставка» и нажмите « Модуль», как показано ниже.

  • Теперь введите подкатегорию под любым именем, как показано ниже.

Код:

  • Теперь используйте DIM для определения любой переменной. Здесь мы выбрали алфавит A в качестве строки .

Код:

  • Теперь создайте другую подкатегорию в том же модуле, как показано ниже.

Код:

  • Теперь во второй подкатегории определите другую переменную B, используя DIM в качестве String.

Код:

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

  • Теперь, чтобы сделать это, напишите Option Explicit над первой подкатегорией, как показано ниже.

Код:

  • Теперь мы можем определить нашу переменную, которая будет использоваться в обеих подкатегориях, которые у нас есть ниже. Итак, теперь рассмотрим запись любой переменной, скажем, A как String, используя DIM.

Код:

Поскольку мы определили переменную, все подкатегории будут в этом модуле, и это будет применимо только ко всему коду этого модуля. И если мы попытаемся вызвать переменные, определенные в этом модуле, в каком-либо другом модуле, то это даст нам ошибку.

VBA Global Variables — Пример № 2

В этом примере мы увидим, как использовать Global или Public word для определения любой переменной в Excel VBA. Для этого мы будем использовать код, который мы видели в примере-1.

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

Код:

Как мы это делали в примере 1, где мы объявили общую переменную, которая будет использоваться в обеих подкатегориях, под Option Explicit. В этом примере мы также объявим глобальную переменную под явным вариантом.

Поскольку у нас уже есть готовый код, мы можем напрямую объявить переменные, используя Global . Теперь в приведенном ниже параметре Explicit напишите Global так же, как мы использовали для DIM, и выберите переменную по выбору. Здесь мы выбираем алфавит A, как показано ниже.

Код:

Теперь мы выбираем переменную любого типа. Как мы уже использовали String в приведенном выше примере, мы бы тоже использовали это здесь.

Код:

Это завершает наш процесс объявления глобальной переменной. Теперь мы можем использовать это в любом модуле, любом проекте только как String. Прежде чем использовать его, удалите ранее объявленную переменную, тогда код будет выглядеть так, как показано ниже.

Код:

Теперь давайте назначим некоторый текст определенной переменной A в обеих подкатегориях. Мы выбираем «Test1» и «Test2» для переменной A в обеих подкатегориях, как показано ниже. А также мы выбрали MsgBox, чтобы показать значения, хранящиеся в переменной A.

Код:

Теперь запустите код, нажав клавишу F5 или нажав кнопку воспроизведения, чтобы увидеть результат.

Мы получим сообщение как «Test1», как показано выше. Это потому, что мы сохранили наш курсор в первой подкатегории.

Теперь поместите курсор в любую вторую подкатегорию и снова запустите код. Теперь мы получим окно сообщения с сообщением «Test2», как показано ниже.

Вот как мы можем создать и определить переменную один раз с помощью Global, и это можно использовать в любом модуле, любом классе и в любом проекте. Мы также можем использовать Public вместо Global, как показано ниже. И это даст тот же результат, который мы получили при использовании Global.

Код:

Плюсы VBA Global Variable

  • Это экономит время при объявлении нескольких переменных, когда мы знаем, что нам может потребоваться снова определить переменные одного и того же типа в разных модулях или подкатегориях.
  • Используя Global или Public в определении переменной процесса, наш код становится меньше, экономя время и пространство.
  • Это уменьшает сложность, когда мы пишем огромный код, и может запутаться в использовании разных переменных в разных модулях или подкатегориях.

Минусы VBA Global Variable

  • Если мы внесем какие-либо изменения в глобальную переменную, то эти изменения будут реализованы во всех местах ее использования, что приведет к проблеме в функциональности написанного кода.

То, что нужно запомнить

  • Global и Public могут использоваться взаимозаменяемо с одинаковыми функциями.
  • Если мы не хотим использовать глобальную переменную, мы можем следовать процессу, как показано в примере 1, для определения переменной. Но это будет ограничено тем же модулем.
  • Глобальные переменные могут использоваться в любом модуле, любой подкатегории, любом классе или в любом проекте.
  • Глобальная переменная дает вывод кода, в котором мы сохранили курсор. Он не будет запускать полный код за один раз, передавая все выходные по одному.

Рекомендуемые статьи

Это руководство по глобальным переменным VBA. Здесь мы обсудим, как объявлять глобальные переменные в Excel, используя код VBA, а также некоторые практические примеры и загружаемый шаблон Excel. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. VBA UserForm
  2. Решить уравнение в Excel
  3. VBA Activate Sheet
  4. Как редактировать выпадающий список в Excel?

Источник

VBA Global Variables

Excel VBA Global Variables

We usually declare any variable by using the word DIM and this is the best direct method of doing this. But the variables declared using DIM can only be used within the same module. If we try to use this variable defined by using DIM, it will be applicable for the module under which it is being declared. What if we want to use a variable in any module or project? Which cannot be possible if we keep on using DIM to define that variable?

In that case, we have a secondary option by defining the variable by word Global or Public in VBA. VBA Global or Public variables are those variables which are declared at the beginning of subcategory with the help of Option Explicit. Whatever things which we don’t or can’t do under subcategories, they are done before that under Option Explicit.

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

How to Declare Global Variables in VBA?

Below are the different examples to declare a global variable in Excel using VBA code.

VBA Global Variables – Example #1

In this example, we will see how different subcategories can be used as a single module without using Global or Public word for defining any variable. For this, we would need a module.

  • Go to Insert menu and click on Module as shown below.

  • Now type the subcategory in any name as shown below.

Code:

  • Now use DIM to define any kind of variable. Here we have chosen alphabet A as String.

Code:

  • Now create another subcategory in the same module as shown below.

Code:

  • Now in the second subcategory define another variable B using DIM as String.

Code:

As shown above, both the variables A and B defined in both subcategories cannot be used in each other’s region. Those will be applicable in their own subcategory only.

  • Now to make this work, write Option Explicit above the first subcategory as shown below.

Code:

  • Now we can define our variable which will be used in both of the subcategories of which we have below. So now consider writing any variable say A as String using DIM.

Code:

As we have defined the variable all the sub-categories will be in that module and this would be applicable to all the code of that module only. And if we try to call the variables defined in this module to some other module, then it would give us the error.

VBA Global Variables – Example #2

In this example, we will see how to use Global or Public word for defining any variable in excel VBA. For this, we will use the code which we have seen in example-1.

We will use below portion of code for Global or Public variable declaration.

Code:

As we did in example-1 where we have declared the common variable which would be used in both the subcategories, below the Option Explicit. In the example, we will declare the Global Variable below the Option Explicit as well.

As we already have our code ready so we can directly go on declaring variables using Global. Now in the below Option Explicit write Global the same we used to with DIM and select a variable of choice. Here we are choosing alphabet A as shown below.

Code:

Now we choose any type of variable to be it. As we have already used String in the above example, so we would use the same here as well.

Code:

This completes our Global variable declaration process. Now we can use this in any module, any project as String only. Before we use it, delete the previously declared variable, then the code would look like as shown below.

Code:

Now let’s assign some text to defined variable A in both subcategories. We are choosing “Test1” and “Test2” for variable A in both subcategories as shown below. And also we have chosen MsgBox to show the values stored in variable A.

Code:

Now run the code by pressing the F5 key or by clicking on the play button to see the result.

We will get the message as “Test1” as shown above. It is because we had kept our cursor in the first subcategory.

Now put the cursor anywhere in the second subcategory and run the code again. We will now get the message box with message “Test2” as shown below.

This is how we can create and define a variable once with the help of Global and that can be used in any module, any class and in any project. We can use Public as well in place of Global as shown below. And this will give the same result as we got in using Global.

Code:

Pros of VBA Global Variable

  • It saves time in declaring the multiple variables when we know, we may need to define the same type of variable again in different modules or subcategories.
  • By using Global or Public in defining a variable process, our code becomes smaller saving time and spaces.
  • It reduces the complexity when we are writing the huge code and may get confused among the use of different variables in different modules or subcategories.

Cons of VBA Global Variable

  • If we do any changes to the Global variable then that changes will get implemented in all where it is used causing the problem in the functionality of written code.

Things to Remember

  • Global and Public can be used interchangeably with the same functionality.
  • If we don’t want to use Global variable then we can follow the process as shown in example-1 for defining the variable. But that would be limited to the same module.
  • Global variables can be used in any module, any subcategory, any class or in any project.
  • A Global variable gives the output of the code where we have kept the cursor. It will not run the complete code at one go giving all the output one by one.

Recommended Articles

This is a guide to VBA Global Variables. Here we discuss how to declare Global Variables in Excel using VBA code along with some practical examples and downloadable excel template. You can also go through our other suggested articles –

Источник

Some functions defined inside a function used within the functions. Also, some variables defined outside the functions used by all the functions. Such variables used are global variables. For example, the variables declared under the sub-function are known as “global variables.”

Table of contents
  • Global Variable in Excel VBA
    • What are Global Variables in Excel VBA?
    • How to Declare Global Variable in VBA?
      • #1 – Module Variables can be used in any Sub Procedure in the Same Module
      •  #2 – Global Variables can be used in any Sub Procedure and also in any Module
    • Things to Remember
    • Recommended Articles

Global Variable in Excel VBA

Declaring a variable seems pretty simple. But to have good hands-on experience, we need to understand the scope of those variables. We often declare the variables for each macro inside the subprocedure. But by declaring one variable, we can use it in all the macros in the same module and the other modules of the current VBA project. This article will show you how to declare global variables in Excel VBA.

What are Global Variables in Excel VBA?

VBA global variables are variables declared before any macro in the module starts. When the variables are declared using either “Public” or “Global,” it becomes a global variable.

Sub Procedure Variables Cannot Use Anywhere.

We usually declare the variable inside the subroutine in VBASUB in VBA is a procedure which contains all the code which automatically gives the statement of end sub and the middle portion is used for coding. Sub statement can be both public and private and the name of the subprocedure is mandatory in VBA.read more by using the word “Dim.”

VBA Global Variable 1

Look at the above image. We have declared the variable “k” as an integer inside the Sub procedure Global_Example1.

Suppose we use this variable inside this Sub procedure at any time. However, we cannot use this variable in another Sub procedure either in the same class module in VBAUsers have the ability to construct their own VBA Objects in VBA Class Modules. The objects created in this module can be used in any VBA project.read more or another module.

VBA Global Variable 1.1

As shown in the above image, the variable “k,” declared in the Sub procedure Global_Example1, cannot be used in the Sub procedure Global_Example2.

Similarly, variable “j” declared in the Sub procedure Global_Example2 cannot be used in the Sub procedure Global_Example1 even though both are in the same module.

How to Declare a Global Variable in VBA?

The following are the ways to declare a global variable in Excel VBA.

#1 – Module Variables can be used in any Sub Procedure in the Same Module

As we have seen, we cannot use the Sub procedure variables in any of the modules. Therefore, to make them available for all the Sub procedures in the same module, we need to declare the variables at the top of the module.

VBA Global Variable Example 1

In the above image, we have declared the variable at the start of the module only. I have expressed the variable “MyNumber” as an Integer in Module 1.

Once declared the variable at the top of the module, we can use the same variable for all the other Sub procedures in the same module. In this case, we can use the variable “MyNumber” for all the Sub procedures in Module 1.

VBA GlobalVariable Example 1-1

We cannot use them in any of the other modules. In this case, the variable “MyNumber,” declared in Module 1, cannot be used in Module 2.

VBA GlobalVariable Example 1-2.png

 #2 – Global Variables can be used in any Sub Procedure and also in any Module

We have seen two kinds of variable declaration and their scope while using. The exciting thing is we can declare the variable in any one of the modules and use it for all the Sub procedures in all the modules of the same VBA Project.

To make the variable available for all the Sub procedures across all the modules, we need to declare the variable at the top of the module not by using the word “Dim” but by using the name “Public” or “Global.”

VBA GlobalVariable Example 1-3

In the above image, we have used the word “Public” to declare the variable instead of our veteran word “Dim.”

In the above screenshot, we have declared the variable in Module 1. However, we have two more modules, Module 2 and Module 3.

Since we have declared the variable using the word “Public” at the top of the module, now we can access these variables in any Sub procedure across any module of the same workbook.

Not only “Public,” but we can also use the word “Global” to declare the variable.

VBA GlobalVariable Example 1-4

“Global” and “Public” are the keywords to declare the variable and make them available across modules in VBA.

Things to Remember

  • Once the excel macroA macro in excel is a series of instructions in the form of code that helps automate manual tasks, thereby saving time. Excel executes those instructions in a step-by-step manner on the given data. For example, it can be used to automate repetitive tasks such as summation, cell formatting, information copying, etc. thereby rapidly replacing repetitious operations with a few clicks.
    read more
    runs with a global variable’s value, the variable is the same across all the Sub procedures.
  • It is better to maintain a particular module to declare global variables in VBA and have all the variables in one module.
  • The only way we can reset the variable’s value is by resetting the macro code by pressing the stop button.

Recommended Articles

This article has been a guide to VBA Global Variables. Here, we learn how to declare global variables in Excel VBA, practical examples, and a downloadable template. Below you can find some useful Excel VBA articles: –

  • VBA Exit Sub
  • VBA ByRef Argument Type Mismatch
  • VBA Option Explicit
  • VBA Long Data Type

Глобальная переменная в проекте VBA Excel. Объявление глобальной переменной в модуле проекта VBA и обращение к ней из других модулей того же проекта.

Объявление глобальной переменной

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

Чтобы переменная стала глобальной, она должна быть объявлена в начале модуля перед первой процедурой (раздел Declarations) с помощью оператора Public. Этот способ работает во всех модулях проекта VBA Excel.

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

Пример объявления глобальных переменных в любом модуле проекта VBA:

Public myGlobVar1 ‘по умолчанию — As Variant

Public myGlobVar2 As String

Public myGlobVar3 As Double

Объявление глобальных переменных

Объявление глобальных переменных

Обращение к глобальной переменной

Примеры обращения к глобальной переменной, объявленной в разных типах модулей проекта VBA Excel. Актуально для обращения из модуля любого типа данного проекта.

Переменная в стандартном модуле

Если глобальная переменная (myGlobVar) объявлена в стандартном модуле (Module1) с уникальным именем, не повторяющимся в других модулях, к ней можно обращаться из других модулей по одному имени (в примере — из модуля формы):

Private Sub CommandButton1_Click()

    myGlobVar = «Глобальная переменная»

    TextBox1.Text = myGlobVar

End Sub

Стандартное обращение с указанием имени модуля (Module1), в котором объявлена глобальная переменная (myGlobVar):

Private Sub CommandButton1_Click()

    Module1.myGlobVar = «Глобальная переменная»

    TextBox1.Text = Module1.myGlobVar

End Sub

Переменная в модуле книги

Глобальная переменная (myGlobVar), объявленная в модуле книги, доступна при обращении к ней из других модулей с помощью следующего кода VBA Excel:

Sub Primer1()

    ThisWorkbook.myGlobVar = «Глобальная переменная»

    MsgBox ThisWorkbook.myGlobVar

End Sub

Переменная в модуле листа

Обращение к глобальной переменной (myGlobVar), объявленной в модуле рабочего листа (Лист1), из других модулей по имени листа (в проводнике проекта находится без скобок слева от имени ярлыка):

Sub Primer2()

    Лист1.myGlobVar = «Глобальная переменная»

    MsgBox Лист1.myGlobVar

End Sub

По имени ярлыка (в проводнике проекта находится в полукруглых скобках справа от имени листа):

Sub Primer3()

    Worksheets(«Лист1»).myGlobVar = «Глобальная переменная»

    MsgBox Worksheets(«Лист1»).myGlobVar

End Sub

Переменная в модуле формы

Глобальная переменная (myGlobVar), объявленная в модуле формы (UserForm1), доступна при обращении к ней из других модулей с помощью следующего кода VBA Excel:

Sub Primer4()

    UserForm1.myGlobVar = «Глобальная переменная»

    MsgBox UserForm1.myGlobVar

End Sub

Переменная в личной книге макросов

Обращение к глобальной переменной (myGlobVar), объявленной в модуле ЭтаКнига проекта VBAProject (PERSONAL.XLSB) из модуля проекта VBA обычной книги Excel:

Sub Primer5()

    Workbooks(«PERSONAL.XLSB»).myGlobVar = «Глобальная переменная»

    MsgBox Workbooks(«PERSONAL.XLSB»).myGlobVar

End Sub

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


VBA Global Variables

Excel VBA Global Variables

We usually declare any variable by using the word DIM and this is the best direct method of doing this. But the variables declared using DIM can only be used within the same module. If we try to use this variable defined by using DIM, it will be applicable for the module under which it is being declared. What if we want to use a variable in any module or project? Which cannot be possible if we keep on using DIM to define that variable?

In that case, we have a secondary option by defining the variable by word Global or Public in VBA. VBA Global or Public variables are those variables which are declared at the beginning of subcategory with the help of Option Explicit. Whatever things which we don’t or can’t do under subcategories, they are done before that under Option Explicit.

How to Declare Global Variables in VBA?

Below are the different examples to declare a global variable in Excel using VBA code.

You can download this VBA Global Variables Excel Template here – VBA Global Variables Excel Template

VBA Global Variables – Example #1

In this example, we will see how different subcategories can be used as a single module without using Global or Public word for defining any variable. For this, we would need a module.

  • Go to Insert menu and click on Module as shown below.

VBA Global Variables Example 1-1

  • Now type the subcategory in any name as shown below.

Code:

Sub Global_Variable()

End Sub

VBA Global Variables Example 1-2

  • Now use DIM to define any kind of variable. Here we have chosen alphabet A as String.

Code:

Sub Global_Variable()

  Dim A As String

End Sub

VBA Global Variables Example 1-3

  • Now create another subcategory in the same module as shown below.

Code:

Sub Global_Variable()

  Dim A As String

End Sub

Sub Global_Variable6()

End Sub

VBA Global Variables Example 1-4

  • Now in the second subcategory define another variable B using DIM as String.

Code:

Sub Global_Variable()

  Dim A As String

End Sub

Sub Global_Variable6()

  Dim B As String

End Sub

Declare Variable B Example 1-5

As shown above, both the variables A and B defined in both subcategories cannot be used in each other’s region. Those will be applicable in their own subcategory only.

  • Now to make this work, write Option Explicit above the first subcategory as shown below.

Code:

Option Explicit

Sub Global_Variable()

End Sub

Sub Global_Variable6()

End Sub

VBA Global Variables Example 1-6

  • Now we can define our variable which will be used in both of the subcategories of which we have below. So now consider writing any variable say A as String using DIM.

Code:

Option Explicit

  Dim A As String

Sub Global_Variable()

End Sub

Sub Global_Variable6()

End Sub

VBA Global Variables Example 1-7

As we have defined the variable all the sub-categories will be in that module and this would be applicable to all the code of that module only. And if we try to call the variables defined in this module to some other module, then it would give us the error.

VBA Global Variables – Example #2

In this example, we will see how to use Global or Public word for defining any variable in excel VBA. For this, we will use the code which we have seen in example-1.

We will use below portion of code for Global or Public variable declaration.

Code:

Option Explicit

Sub Global_Variable()

End Sub

Sub Global_Variable6()

End Sub

VBA Global Variables Example 2-1

As we did in example-1 where we have declared the common variable which would be used in both the subcategories, below the Option Explicit. In the example, we will declare the Global Variable below the Option Explicit as well.

As we already have our code ready so we can directly go on declaring variables using Global. Now in the below Option Explicit write Global the same we used to with DIM and select a variable of choice. Here we are choosing alphabet A as shown below.

Code:

Option Explicit

Global A

Sub Global_Variable()

  Dim A As String

End Sub

Sub Global_Variable6()

  Dim B As String

End Sub

VBA Global Variables Example 2-2

Now we choose any type of variable to be it. As we have already used String in the above example, so we would use the same here as well.

Code:

Option Explicit

Global A As String

Sub Global_Variable()

  Dim A As String

End Sub

Sub Global_Variable6()

  Dim B As String

End Sub

VBA Global Variables Example 2-3

This completes our Global variable declaration process. Now we can use this in any module, any project as String only. Before we use it, delete the previously declared variable, then the code would look like as shown below.

Code:

Option Explicit

Global A As String

Sub Global_Variable()

End Sub

Sub Global_Variable6()

End Sub

VBA Global Variables Example 2-4

Now let’s assign some text to defined variable A in both subcategories. We are choosing “Test1” and “Test2” for variable A in both subcategories as shown below. And also we have chosen MsgBox to show the values stored in variable A.

Code:

Option Explicit

Global A As String

Sub Global_Variable()

A = "Test1"
MsgBox A

End Sub

Sub Global_Variable6()

A = "Test2"
MsgBox A

End Sub

MsgBox Example 2-5

Now run the code by pressing the F5 key or by clicking on the play button to see the result.

Test1 Example 2-6

We will get the message as “Test1” as shown above. It is because we had kept our cursor in the first subcategory.

Now put the cursor anywhere in the second subcategory and run the code again. We will now get the message box with message “Test2” as shown below.

Test2 Example 2-7

This is how we can create and define a variable once with the help of Global and that can be used in any module, any class and in any project. We can use Public as well in place of Global as shown below. And this will give the same result as we got in using Global.

Code:

Option Explicit

Public A As String

Sub Global_Variable()

A = "Test1"
MsgBox A

End Sub

Sub Global_Variable6()

A = "Test2"
MsgBox A

End Sub

Use Public Example 2-9

Pros of VBA Global Variable

  • It saves time in declaring the multiple variables when we know, we may need to define the same type of variable again in different modules or subcategories.
  • By using Global or Public in defining a variable process, our code becomes smaller saving time and spaces.
  • It reduces the complexity when we are writing the huge code and may get confused among the use of different variables in different modules or subcategories.

Cons of VBA Global Variable

  • If we do any changes to the Global variable then that changes will get implemented in all where it is used causing the problem in the functionality of written code.

Things to Remember

  • Global and Public can be used interchangeably with the same functionality.
  • If we don’t want to use Global variable then we can follow the process as shown in example-1 for defining the variable. But that would be limited to the same module.
  • Global variables can be used in any module, any subcategory, any class or in any project.
  • A Global variable gives the output of the code where we have kept the cursor. It will not run the complete code at one go giving all the output one by one.

Recommended Articles

This is a guide to VBA Global Variables. Here we discuss how to declare Global Variables in Excel using VBA code along with some practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA UserForm
  2. VBA Get Cell Value
  3. VBA Activate Sheet
  4. VBA RGB

Return to VBA Code Examples

In this tutorial we will cover VBA Global Variables.

In VBA, variables can be declared with different scopes. The scope determines where the variable can be used.

Procedure-level Variable

Typically, you will see variables declared at the procedure-level within Sub Procedures or Functions. Procedure-level variables must be declared using the Dim keyword within the procedure where they will be used.

This example declares someNumber as an integer variable within the procedure.

Sub DeclaringAProcedureLevelVariable()

Dim someNumber As Integer
someNumber = 5
MsgBox someNumber

End Sub

You can only use this variable within this Sub Procedure. If you call the variable from another Sub Procedure you would get the following Compile Error:

Declaring a Variable at Procedure level and then Getting an Error

Module Level Variable

A Module-level variable can be used by any Sub Procedure or Function within that module. You need to place the variable declaration at the top of the module in the Declarations section, under the Option Explicit statement, and use the Dim keyword:

Declaring a Module level variable

Now the variable someNumber can be used in both sub procedures.

Global Level Variable

A global-level variable can be used anywhere within your code, within Modules, Functions, Sub Procedures and Classes. Global variables are declared in the Declarations Section, under the Options Explicit statement and using the keyword Global. The way you declare a Global level variable is shown below. Both of the Sub Procedures in Module1 can use this variable.Declaring a Global Level Variable

Since this variable is a Global level variable, you can also use it in Module2:

Using a Global Variable in Another Module

VBA Coding Made Easy

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

Learn More!

Home / VBA / Declare Global Variable (Public) in VBA

In VBA, when you declare a variable as a global variable you can use it in any procedure in any module. As the name suggests you can use it globally means its availability is everywhere.

So if you have a global variable in the “module1” and now you want to use it in the module2, you can use it.

  1. First, you need to use the keyword “Global”
  2. After that, declare the name of the variable.
  3. Next, type “as” to get the list of data types.
  4. In the end, select the data type that you want to declare for the variable.
global-variable-in-vba

Notes

  1. When you are declaring a global variable, you need to declare it before writing any procedure into the module as you can see in the above example.
  2. You can also use the keyword “Public” to declare a variable as global.

Understand Scope of Variables

But to have a clear understanding of a global variable you need to understand the scope of the variables. There are three ways of defining scopes to variables:

  1. Procedure-Level: You can only use a variable in the same procedure where you declare it.
  2. Module-Level (Private): Makes a variable accessible from all the procedures in a module.
  3. Global Level (Public): Makes a variable accessible from all the procedures in all the modules.

Let me share something from the real world with you to make you understand this. I work from a co-working space and the place where I sit is on the first floor in the three-floor building, I mostly sit on the same seat every day.

When you declare a variable with the procedure-level scope you can only use it in the same procedure.

Just like I sit on the same seat on the same floor every day. But let me tell you more: Even though I sit on the first floor, I can use any seat on other floors too.

And in the below snapshot, we have declared the variable “iCon” at the top of the module using the keyword Private before starting any procedure and I have used it in all three codes.

declared-the-variable-icon

Think of this module as a building where you have different floors (Procedures) and as you have already declared the variable at the starting of the module you can use any of the procedures in that module. It is called private module-level scope.

Now here is the last thing: My office has branches in different cities all over the country and if I go there, I can go to those offices and use any of the seats if I want. So, if you have different modules in your workbook, you can use a variable in all those modules by declaring it as Public/Global.

This Excel VBA tutorial explains how to declare private variable, global variable / public variable in VBA, and explain the scope of variable.

You may also want to read:

Function, Sub, Method, Property

Difference between Dim and Set

Scope of local variable / global variable / private variable

Procedure Level

When you declare a variable inside a Sub Procedure or Function (local variable), the variable can only be used within them.

For example, in Sub Procedure1, you have declared  variableA  = 1. In Sub Procedure2, if you use variableA, it will have value 0 (uninitiated).

Public Sub Procedure1()
    Dim variableA as integer
    variableA = 1
End Sub

Public Sub Procedure2()
    MsgBox (variableA)  'return no value
End Sub

Module Level

If you want to use variableA for all Procedures within the same Module, you can declare it as Private Variable on top of the Module. The value of Private variable will preserve until Workbook is closed or reset the Project. Because variableA is not initialized until Procedure1 is run, you have to run Procedure1 using Call in Procedure2.

Private variableA as Integer

Public Sub Procedure1()
    variableA = 1
End Sub

Public Sub Procedure2()
    Call Procedure1
    MsgBox (variableA)  'return 1
End Sub

Project Level

If you want to use variableA in all Modules, you can declare it as Global Variable. Using Public or Global in declaration on top of any Module. The value of Global variable will preserve until Workbook is closed or reset the Project.

Public variableA as Integer

Public Sub Procedure1()
    variableA = 1
End Sub

Public Sub Procedure2()
    Call Procedure1
    MsgBox (variableA)  'return 1
End Sub

Managing Global Variable

If you have created many Modules, and in each Module you have defined Global Variables, it is better to create a Module specifically for declaration of Global Variable, so that you can easily follow the underlying value of the global variables.

It is also a good practice to name all Global Variable with the same prefix, for example, you can call it  global_variableA, or g_variableA.

Because you only need to initialize Global Variable once instead of calling them in every Procedure, you can consider initializing them in Workbook_Open Event.

Destroy Variable

There is not way to destroy / uninitialize a variable inside the Procedure. It can only be destroy when

  1. Variable is out of scope. For example, local variable will end when it exists the Procedure
  2. Reset the VBA Project
  3. Use End Statement in the Procedure, but this will also end the subsequent Procedure.
    Public Sub Procedure1()
        variableA = 1
        End
    End Sub

Понравилась статья? Поделить с друзьями:
  • Excel vba getobject excel application
  • Excel vba listobjects querytable
  • Excel vba get worksheet
  • Excel vba get selected value
  • Excel vba get row from range