Vba excel общая переменная

Глобальная переменная в проекте 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 к глобальной переменной, объявленной в стандартном модуле личной книги макросов.


This is a question about scope.

If you only want the variables to last the lifetime of the function, use Dim (short for Dimension) inside the function or sub to declare the variables:

Function AddSomeNumbers() As Integer
    Dim intA As Integer
    Dim intB As Integer
    intA = 2
    intB = 3
    AddSomeNumbers = intA + intB
End Function
'intA and intB are no longer available since the function ended

A global variable (as SLaks pointed out) is declared outside of the function using the Public keyword. This variable will be available during the life of your running application. In the case of Excel, this means the variables will be available as long as that particular Excel workbook is open.

Public intA As Integer
Private intB As Integer

Function AddSomeNumbers() As Integer
    intA = 2
    intB = 3
    AddSomeNumbers = intA + intB
End Function
'intA and intB are still both available.  However, because intA is public,  '
'it can also be referenced from code in other modules. Because intB is private,'
'it will be hidden from other modules.

You can also have variables that are only accessible within a particular module (or class) by declaring them with the Private keyword.

If you’re building a big application and feel a need to use global variables, I would recommend creating a separate module just for your global variables. This should help you keep track of them in one place.

В данной статье мы рассмотрим работу с локальными и глобальными переменными VBA языка, а именно: как ведут себя переменные, объявленные в блоке модуля и в блоке отдельной процедуры; познакомимся с ключевыми словами Public, Private и Static; Определим логику назначении типов данных при объявлении нескольких переменных в одной строке; напишем парочку примеров.

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

Содержание

  1. Объявление нескольких переменных VBA
  2. Объявление переменных в VBA локальной и глобальной видимости
  3. Ключевые слова Private, Public и Static

Объявление нескольких переменных VBA

Рассмотрим такой пример: надо объявить три переменные разного типа, например, Byte, String и Long, это может выглядеть так:

dim A as Byte, B as String, C as Long

Но вот что делать, если все три переменные должны быть одного типа, такой код будет неверен:

Тут A и В будут типа Variant и только C – Long. Что бы все правильно сработало, нам нужно каждой переменной назначить заданный тип:

dim A as Long, B as Long, C as Long

Объявление переменных в VBA локальной и глобальной видимости

Если переменная VBA объявлена в начале модуля, то она сохраняется в памяти до тех пор, пока работает макрос, если объявление происходит в теле процедуры, то переменная будет удалена из памяти сразу, после выполнения блока кода заданной процедуры. Добавьте в редакторе Visual Basic новую форму и модуль.

Параметры формы: разместите на форме три компонента Label и три кнопки, как показано на рисунке. Имя формы (свойство Name) – VariableForm, имя модуля – VariableModule.

В редакторе кода для модуля пропишите:

Sub VariableModule()
    VariableForm.Show
End Sub

Тут мы просто определяем, что при запуске макроса нужно запустить форму.

В редакторе кода для формы пропишите:

'**************************************************
' Объявление локальных и глобальных переменных в VBA
'**************************************************
 
' Включаем проверку переменных VBA
Option Explicit
 
' Глобальная переменная
Dim GVar As Integer
'Нельзя присвоить значение вне процедуры!!!
'GVar = 10
Sub GetGlobal()
    ' Увеличиваем значение на 5
    GVar = GVar + 5
    Label1.Caption = "Глобальное значение " & GVar
End Sub
Sub GetLocal_1()
Dim LVar As Integer
    ' Увеличиваем значение на 2
    LVar = LVar + 2
    Label2.Caption = "Локальное значение " & LVar
End Sub
Sub GetLocal_2()
Dim LVar As Integer
    ' Увеличиваем значение на 3
    LVar = LVar + 3
    Label3.Caption = "Локальное значение " & LVar
End Sub
 
Private Sub CommandButton1_Click()
    Call GetGlobal
End Sub
 
Private Sub CommandButton2_Click()
    Call GetLocal_1
End Sub
 
Private Sub CommandButton3_Click()
    Call GetLocal_2
End Sub
 
Private Sub UserForm_Click()
 
End Sub
 
Private Sub UserForm_Initialize()
    ' настройка первого текстового поля
    Label1.FontSize = 12
    Label1.ForeColor = &HFF0000
    Call GetGlobal
 
    ' настройка второго текстового поля
    Label2.FontSize = 12
    Label2.ForeColor = &H6400
    Call GetLocal_1
 
    ' настройка третьего текстового поля
    Label3.FontSize = 12
    Label3.ForeColor = &HFF
    Call GetLocal_2
End Sub

В самом начале мы объявляем глобальную переменную VBA – GVar типа Integer, в комментарии указано, что вне процедуры присвоить значение переменной нельзя. Далее следуют три процедуры, в первой процедуре происходит увеличение значение глобальной GVar на 5, результат будет записываться в свойство Caption первого компонента Label. Вторя и третья процедуры производят аналогичные действия, только для объявленных в них локальных переменных VBA, LVar, происходит увеличение значения на 2 и на 3, соответственно. События Click (нажатие кнопки мыши) для кнопок будет вызывать заданные процедуры.

Объявление VBA переменных

При запуске макроса в полях будут отображаться значения 5, 2 и 3. При нажатии на “Кнопка 1” будет происходить вызов процедуры GetGlobal и увеличение значения переменной GVar на 5. Для “Кнопка 2” и “Кнопка 3” будут вызываться процедуры GetLocal_1 и GetLocal_2, однако ничего увеличиваться не будет, так как переменные LVar являются локальными и при каждом вызове заданных процедур их значение будет обнуляться.

Ключевые слова Private, Public и Static

Private – аналогично ключевому слову Dim, использование Private вместо Dim актуально в том случае, если вы хотите, что бы данное ключевое слово напоминало о том, что переменная доступна только в пределах данной процедуры или функции.

Public – позволяет сделать переменную VBA доступной из любой части проекта, однако, это будет актуальным лишь в том случае, если объявление переменных в VBA происходит в разделе Declarations (Объявления) самого модуля. Если же вы пропишите Public вместо Dim в теле процедуры, то видимость все ровно будет доступна только в данной процедуре.

Static – данное ключевое слово актуально использовать вместо Dim тогда, когда нужно сохранять значение переменной в теле процедуры. Для примера, мы перепишем предыдущий код таким образом:

Sub GetLocal_1()
Static LVar As Integer
    ' Увеличиваем значение на 2
    LVar = LVar + 2
    Label2.Caption = "Локальное значение " & LVar
End Sub
Sub GetLocal_2()
Static LVar As Integer
    ' Увеличиваем значение на 3
    LVar = LVar + 3
    Label3.Caption = "Локальное значение " & LVar
End Sub

Мы просто изменили ключевое слово Dim на Static, и теперь переменные LVar не будут удаляться из памяти после выполнения процедур. Объявление переменных в VBA. Обратите внимание, что мы объявили переменные с одним именем, это можно, так как они находятся в отдельных процедурах.

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

We have already covered an introduction to variables, constants and VBA data types in an introductory tutorial. We are going to cover Public variables in this tutorial. The definition of a Public variable is a variable that any module, Sub Procedure, Function or Class can access and use within a certain workbook.

Declaring a Public Variable in VBA

There are five main keywords that you can use to declare a variable in VBA. These are:

  • The Dim keyword
  • The Static keyword
  • The Global keyword
  • The Public keyword
  • The Private keyword

The Global variable and the Public variable are very similar.

In order to declare a Public variable, you have to place your variable in the Declarations section of your VBA code below the Option Explicit statement, outside of any of your Sub Procedures or Functions and you also have to use the Public keyword. This is shown below:

Declaring a Public Variable

Public MyVariable as Integer

When you declare a variable as a public variable, you are also inferring to the scope of that variable. You determine the scope of a variable by the keyword you use to declare it and where you place it in your code.

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!

alt text

Learn More!

<<Return to VBA Examples

Понравилась статья? Поделить с друзьями:
  • Vba excel найти все значения в диапазоне
  • Vba excel обращение к ячейке по индексу
  • Vba excel найти во всех листах
  • Vba excel обращение к ячейке по имени
  • Vba excel найти в книге