Call vba excel описание

Вызов процедур Sub (подпрограмм) из кода других процедур, расположенных в одном или разных модулях, в одной или разных книгах Excel (проектах VBA), с аргументами или без. Примеры.

Вызов подпрограммы из кода другой процедуры Sub, расположенной в том же модуле или другом модуле одной рабочей книги (проекта VBA) осуществляется с помощью ключевого слова Call или без него по имени подпрограммы. Вызывающая процедура Sub может быть любой видимости, как Public, так и Private, а вызываемая, если расположена в том же модуле, может быть любой видимости, но если расположена в другом модуле, должна быть объявлена как Public.

Синтаксис вызова подпрограмм в пределах одной книги

[ Call ] ИмяПроцедуры [ (Аргументы) ]

  • Call — необязательное ключевое слово;
  • ИмяПроцедуры — обязательный компонент, имя вызываемой подпрограммы;
  • Аргументы — необязательный компонент, список аргументов вызываемой процедуры Sub, разделенных запятой.

Вызов подпрограмм без аргументов в пределах одного модуля

Скобки рядом с именами вызываемых подпрограмм без аргументов не ставятся:

Private Sub test1()

  Call test2

  test3

End Sub

Private Sub test2()

  MsgBox «Процедура test2 (Private) вызвана с ключевым словом Call!»

End Sub

Public Sub test3()

  MsgBox «Процедура test3 (Public) вызвана без ключевого слова Call!»

End Sub

Вы можете скопировать приведенный код в свой модуль и посмотреть, запустив процедуру test1, как она последовательно запускает процедуры test2 и test3.

Вызов подпрограмм с аргументами в пределах одного модуля

При вызове процедур Sub с аргументами и ключевым словом Call, аргументы заключаются в скобки, без ключевого слова Call — аргументы не заключаются в скобки:

Private Sub test4()

  Call test5(15, 25)

  test6 256, 312, 4.52

End Sub

Sub test5(a As Single, b As Single)

  MsgBox a + b

End Sub

Sub test6(c As Single, d As Single, e As Single)

  MsgBox c + d + e

End Sub

Вы можете разместить этот код в своем модуле и протестировать его.

Вызов подпрограмм из разных модулей одной книги

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

Вызываемая подпрограмма расположена в Стандартном модуле

‘Процедура Sub с уникальным именем —

‘возможны два варианта:

УникальноеИмяПроцедуры

ИмяМодуля.УникальноеИмяПроцедуры

‘Процедура Sub с неуникальным именем —

‘возможен только один вариант:

ИмяМодуля.НеуникальноеИмяПроцедуры

  • ИмяМодуля — уникальное имя стандартного модуля, отображаемое в проводнике проекта VBA.

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

Вызываемая подпрограмма расположена в модуле книги, модуле листа, модуле формы

‘В модуле книги:

ЭтаКнига.ИмяПроцедуры

‘В модуле листа:

ИмяЛиста.ИмяПроцедуры

Worksheets(«Имя ярлычка листа»).ИмяПроцедуры

‘В модуле формы:

ИмяФормы.ИмяПроцедуры

  • ЭтаКнига — так и пишется, указывает на текущую книгу в которой расположены вызывающая и вызываемая подпрограммы.
  • ИмяЛиста — уникальное имя листа, которое в проводнике проекта VBA указано без скобок (по умолчанию: Лист1, Лист2, Лист3 и т.д.).
  • Имя ярлычка листа — дублирующее имя листа, которое в проводнике проекта VBA указано в скобках.
  • ИмяФормы — уникальное имя пользовательской формы, отображаемое в проводнике проекта VBA.

Вызов процедур Sub из модулей разных книг

Если вызываемая подпрограмма расположена в другой книге, она должна быть объявлена как Public, а книга открыта. Запустить такую процедуру Sub можно с помощью метода Application.Run (протестировано в Excel 2016).

Синтаксис метода Application.Run

Application.Run «ИмяКниги!ИмяМодуля.ИмяПроцедуры», Арг1, Арг2, …, Арг30

  1. ИмяКниги!ИмяМодуля.ИмяПроцедуры — обязательный компонент, полный адрес подпрограммы, заключен в двойные кавычки.
    • ИмяКниги — имя рабочей книги Excel с расширением, в которой находится вызываемая подпрограмма, если имя содержит пробелы, оно заключается в одинарные кавычки — апострофы (‘Имя Книги’).
    • ИмяМодуля — имя модуля для стандартного модуля (для уникальных имен вызываемых подпрограмм может не указываться), имя листа для модуля листа, словосочетание «ЭтаКнига» (без кавычек) для модуля книги.
    • ИмяПроцедуры — имя вызываемой процедуры Sub.
  2. Арг1, Арг2, …, Арг30 — необязательные компоненты, аргументы вызываемой подпрограммы, максимальное количество которых ограничено 30 элементами.

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

Полный адрес вызываемой процедуры

Может показаться сложным составить полный адрес вызываемой подпрограммы, но на самом деле все очень просто — Excel уже сделал это за нас.

1. Откройте окно со списком макросов.

Список макросов во всех открытых книгах Excel

Список макросов во всех открытых книгах

2. Найдите в списке вызываемую подпрограмму и кликните по ней. Ее полный адрес отобразится в поле «Имя макроса».

3. Скопируйте полное имя вызываемой процедуры Sub и вставьте ее в метод Application.Run, заключив в двойные кавычки.

Один нюанс: в окне «Макрос» не отображаются процедуры с аргументами. Чтобы отобразить такую процедуру, закомментируйте аргументы, а после копирования и вставки раскомментируйте их.

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

Пример вызова подпрограмм из другой книги

Допустим, у нас есть рабочая книга Excel под именем «Книга1.xlsm» (или «Книга1.xls» в ранних версиях программы). В ней находятся вызываемые из другой книги процедуры Sub, перечисленные ниже.

В стандартном модуле «Module1»:

Sub Vyzov1()

  MsgBox «Запущена процедура в стандартном модуле!»

End Sub

В модуле листа «Лист1»:

Sub Vyzov2()

  MsgBox «Запущена процедура в модуле листа!»

End Sub

В модуле книги «ЭтаКнига»:

Sub Vyzov3(a As Variant, b As Variant)

  MsgBox «Запущена процедура в модуле книги!» _

  & vbNewLine & «Сумма равна: « & a + b

End Sub

Для последовательного запуска этих подпрограмм можно вставить в любой модуль другой книги Excel следующую процедуру:

Sub ProverkaVyzova()

  Application.Run «Книга1.xlsm!Vyzov1»

  Application.Run «Книга1.xlsm!Module1.Vyzov1»

  Application.Run «Книга1.xlsm!Лист1.Vyzov2»

  Application.Run «Книга1.xlsm!ЭтаКнига.Vyzov3», 555, 445

End Sub

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

И еще раз напомню, что имя книги с пробелами заключается в одинарные кавычки (апострофы):

Application.Run «‘Новая Книга 1.xlsm’!Процедура1»

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

Заключение

В этой статье не рассмотрено добавление ссылок из одного проекта VBA на другой, которые позволяют работать с модулями и процедурами, находящимися в другом проекте так, как с находящимися в текущем. Причем книга, с которой установлена связь, может быть закрыта. Я предпочитаю работать с Личной книгой макросов, а при попытке, из любопытства, установить связь между двумя книгами, программа Excel, почему-то, отказала мне в этом и эксперименты закончились.

Если хотите поэкспериментировать со связанными книгами, откройте проект VBA, из которого надо установить связь с другой книгой, и выберите в главном меню «Tools» — «References…». В открывшемся окне «References — VBAProject» все открытые книги будут отображены одним словом — «VBAProject». Выделяйте по очереди строки с этим словом и внизу, в информационной рамке, смотрите, какой книге этот проект принадлежит. Поставьте галочку рядом с выбранным проектом и нажмите кнопку «OK». Если книга, с проектом которой устанавливается связь, закрыта, ее не будет в списке. В этом случае, нажмите на кнопку «Browse…», найдите, выбрав расширение, нужную книгу и откройте ее в проводнике. Связь будет установлена, и процедуры из связанных книг будут вызываться по имени с ключевым словом Call или без него, как будто они расположены в одной книге.

Передает управление в процедуру Sub, процедуру Function или процедуру библиотеки динамической компоновки (DLL).

Call имя [списокАргументов]

Параметры
имя

Обязательный. Имя вызываемой процедуры.
списокАргументов
Необязательный. Разделяемый запятыми список переменных, массивов или выражений, передаваемых в процедуру. Компоненты спискаАргументов могут включать ключевые слова ByVal или ByRef для описания того, каким образом аргументы будут рассматриваться вызываемой процедурой. Однако ключевые слова ByVal и ByRef могут использоваться с инструкцией Call только при вызове процедуры из библиотеки динамической компоновки.

Замечания
Не обязательно применять ключевое слово Call при вызове процедуры. Однако, если ключевое слово Call используется для вызова процедуры с аргументами, списокАргументов должен быть заключен в скобки. Если ключевое слово Call не используется, необходимо также опустить скобки вокруг спискаАргументов. При использовании синтаксиса Call для вызова как внутренней, так и определяемой пользователем функции, возвращаемое функцией значение отбрасывается.
Для передачи в процедуру полного массива следует воспользоваться именем массива с пустыми скобками.

Пример
В данном примере показано, как использовать инструкцию Call для передачи управления процедуре Sub, внутренней функции, процедуре библиотеки динамической компоновки (DLL) и процедуре программного ресурса Macintosh.

' Вызов процедуры Sub.
Call PrintToDebugWindow("Всем привет")	
' Предыдущая инструкция передает управление следующей процедуре Sub.
Sub PrintToDebugWindow(AnyString)
	Debug.Print AnyString		' Вывод в окно отладки.
End Sub

' Вызов внутренней функции. Значение, возвращаемое этой функцией,
' не используется.
Call Shell(AppName, 1)			' AppName содержит путь к выполняемому файлу.

' Вызов процедуры DLL Microsoft Windows.  Инструкция Declare должна
' быть личной (Private) в модуле класса, но не в стандартном модуле.
Private Declare Sub MessageBeep Lib "User" (ByVal N As Integer)

Sub CallMyDll()
	Call MessageBeep(0)		' Вызов процедуры Windows DLL.
	MessageBeep 0			' Повторный вызов без  ключевого слова Call.
End Sub

' Вызов программного ресурса Macintosh.
Declare Sub MessageAlert Lib "MyHd:MyAlert" Alias "MyAlert" (ByVal N _
As Integer)
Sub CallMyCodeResource()
	Call MessageAlert(0)		' Вызов программного ресурса Macintosh.
	MessageAlert 0			' Повторный вызов без  ключевого слова Call.
End Sub

Excel VBA: Calling Sub Procedures & Functions, Placement in Modules

———————————————————————————

Contents:

Sub procedures, Function Procedures & Property Procedures

Naming Rules & Conventions for Procedures

VBA Procedures Scope — Public vs Private

Placement of Macros / Sub procedures in appropriate Modules

Calling Procedures

Executing Procedures

——————————————————————————— 


Sub procedures, Function Procedures & Property Procedures

A VBA project can contain multiple modules, class modules and user forms. Each module contains one or more procedures viz. sub-procedures or functions. Procedures break a program into smaller and specific components. A VBA procedure, also referred to as a Macro, is defined as a set of codes which make Excel perform an action. A procedure is usually of two types, a sub procedure or a function. The third type of procedure is Property, used for Class Modules. As explained below in detail: sub-procedures do not return a value; functions return a value; property procedures are used to return and assign values, and set a reference to an object.

Sub procedures

Event Procedures — are predefined by VBA:

One category of sub procedures are Event Procedures which are triggered by a predefined event and are installed within Excel having a standard & predetermined name viz. like the Worksheet change procedure is installed with the worksheet — «Private Sub Worksheet_Change(ByVal Target As Range)», which combines the object name, underscore, and the event name. The other category of sub-procedures are those which are created by the user. For a detailed understanding of Event Procedures, refer our section: Excel VBA Events, Event Procedures (Handlers), Triggering a VBA Macro.

User Created Sub procedures:

Creating a sub procedure: A sub procedure declaration statement starts with the keyword Sub, followed by a name and then followed by a set of parentheses. A sub-procedure ends with an End Sub statement which can be typed but it also appears automatically on going to the next line after the Sub declaration statement is typed. Your vba code or statements are entered inbetween. See below example of a procedure named Greetings, running or executing which will return the message Welcome:

Sub Greetings()

MsgBox «Welcome!»

End Sub

Function Procedures

A sub-procedure is a set of vba codes or statements which perform an action, but does not «return a value». A Function is also used to perform an action or calculation (which can also be performed by a sub procedure) but «returns a value», which is a single value. The name of the function can be used within the function procedure to indicate the value returned by the function — refer Example 4 which shows the variance between how a function and sub works. Like you use built-in Excel functions of SUM, MAX, MIN, COUNT, AVERAGE, etc., Function procedures are created in vba to make custom worksheet functions. Function procedure cannot be created using a Macro Recorder. A sub procedure uses a different syntax as compared to a Function. A Function procedure can be called by using its name within an expression which is not possible in respect of a sub procedure which can be called only by a stand-alone statement. Because a function returns a value, it can be used directly in a worksheet (which is not possible with a sub-procedure), by entering/selecting the name of the function after typing an equal sign (refer Image 1).

Creating a Function procedure: A function declaration statement starts with the keyword Function, followed by a name and then followed by a set of parentheses. You must specify the data type which is the type of value the function will return — this is done by typing the keyword As (after the parentheses) followed by the data type. Functions can be created without arguments or with any number of arguments which are listed between the parentheses and in case of multiple arguments, separate them with commas. A function procedure ends with an End Function statement which can be typed but it also appears automatically on going to the next line after the Function declaration statement is typed. Your vba code or statements are entered inbetween the Function declaration statement & the End statement.

Executing a Function procedure: (i) the function can be called from another procedure viz. a sub-procedure or function procedure; and (ii) the function can be used directly in the spreadsheet viz. in a worksheet formula by entering/selecting the name of the function after typing an equal sign. See below examples of Function procedures and how they are called:

Example 1

Function partNames() As String
‘The declaration of the partNames function contains no argument.

Dim strFirstName As String
Dim strSurName As String

strFirstName = InputBox(«Enter first name»)
strSurName = InputBox(«Enter sur name»)

partNames = strFirstName & » » & strSurName

End Function

Sub fullName()

‘call the partNames function and place value in cell A1 of active sheet:
ActiveSheet.Range(«A1») = partNames

End Sub

Example 2

Function cubeRoot() As Double
‘The declaration of the cubeRoot function contains no argument.

Dim i As Integer

i = InputBox(«Enter an Integer»)
cubeRoot = i ^ (1 / 3)
cubeRoot = Format(cubeRoot, «#.##»)

End Function

Sub callCubeRoot()

‘call the cubeRoot function in the message box:
MsgBox «Cube Root of the number is » & cubeRoot

End Sub

Example 3 (refer section on Passing Arguments to Procedures, Excel VBA to understand how arguments are passed in a procedure)

Function triple(i As Integer) As Long
‘The declaration of the triple function contains one variable as argument.

triple = i * 3

End Function

Sub integerTriple()

Dim a As Integer

a = InputBox(«Enter an Integer»)

‘call the triple function:
MsgBox triple(a)

End Sub

Refer Image 1 which displays how the function is used in a worksheet.

It may be noted that the set of parentheses, after the procedure name in the Sub or Function declaration statement, is usually empty. This is the case when the sub procedure or Function does not receive arguments. However, when arguments are passed to a sub procedure or a Function from other procedures, then these are listed between the parentheses.

Refer section on Passing Arguments to Procedures, Excel VBA to understand how arguments are passed in a procedure.

Example 4: shows the variance between how a function and sub works — functions return a value whereas sub-procedures do not return a value.

For live code, click to download excel file.

The addSquare function returns a value which can be used by the calling procedure:

Function addSquare() As Double
‘the addSquare function returns a value in its own name:

Dim a As Double
Dim b As Double

a = InputBox(«Enter first number»)
b = InputBox(«Enter second number»)

addSquare = (a + b) ^ 2

End Function

Sub calculate()
‘This is the calling procedure: calls the addSquare function.

Dim c As Double

‘the addSquare function returns a value which can be used by the calling procedure:
c = addSquare ^ (1 / 2)
MsgBox c

End Sub

The addSquare1 sub-procedure does NOT return a value which can be used by the calling procedure:

Sub addSquare1()

Dim a As Double
Dim b As Double
Dim c As Double

a = InputBox(«Enter first number»)
b = InputBox(«Enter second number»)

c = (a + b) ^ 2
MsgBox c

End Sub

Sub calculate1()
‘This is the calling procedure: calls the addSquare1 sub procedure.

‘the addSquare1 sub-procedure does NOT return a value which can be used by the calling procedure. The calling procedure (calculate1) can only call the addSquare1 sub-procedure without being able to use its result:
addSquare1

End Sub

Property Procedures

For a detailed understanding of Property Procedures, refer section Custom Classes & Objects, Custom Events, using Class Modules in Excel VBA.

Property Procedure is a set of vba codes that creates and manipulates custom properties for a class module. The properties of the class object are manipulated in a Class Module with Property procedures which use the Property Let, Property Get, and Property Set statements. A Property procedure is declared by a Property Let,  Property Get or Property Set statement and ends with an End Property statement. Property Let (write-only property) is used to assign a value to a property and Property Get (read-only property — which can only be returned but not set) returns or retrieves the value of a property. Property Set (write-only property) is used to set a reference to an object. Property procedures are usually defined in pairs, Property Let and Property Get OR Property Set and Property Get. A Property Let procedure is created to allow the user to change or set the value of a property, whereas the user cannot set or change the value of a read-only property (viz. Property Get).

A property procedure can do whatever can be done within a vba procedure like performing an action or calculation on data. A Property Let (or Property Set) procedure is an independent procedure which can pass arguments, perform actions as per a set of codes and change the value of its arguments like a Property Get procedure or a Function but does not return a value like them. A Property Get procedure is also an independent procedure which can pass arguments, perform actions as per a set of codes and change the value of its arguments like a Property Let (or Property Set) procedure, and can be used similar to a Function to return the value of a property.

The Property Set procedure is similar to and a variation of the Property Let procedure and both are used to set values. A Property Set procedure is used to create object properties which are actually pointers to other objects, whereas a Property Let procedure sets or assigns values to scalar properties like string, integer, date, etc. Using the Property Set statement enables Properties to be represented as objects.


Naming Rules & Conventions for Procedures

It will help to assign a procedure name which is reflective of the action you wish to perform with the procedure. Some programmers prefer to use a sentence, differentiating words by an underscore or a capital letter viz. total_number_of_rows, TotalNumberOfRows. Use of very lengthy names names is generally avoidable.

There are some rules which are to be followed when naming your procedures:

The name must begin with a letter, and not a number or underscore.

A name can consist of letters, numbers or underscores but cannot have a period (.) or punctuation characters or special characters (such as ! @ # $ % ^ & * ( ) + — = [ ] { } ; ‘ : » , . / < > ? | ` ~).

The name should consist of a string of continuous characters, with no intervening space.

A procedure name can have a maximum of 255 characters.

Procedure names cannot use keywords / reserved words such as If, And, Or, Loop, Do, Len, Close, Date, ElseIf, Else, Select, … that VBA uses as part of its programming language.

Valid Names:

TotalRows

total_rows_10

Total_number_of_Rows

Invalid Names: 

Total.Rows

5Rows

Total&Rows

Total Rows (space not allowed)


VBA Procedures Scope — Public vs Private

A vba procedure can have either Public or Private Scope. A procedure can be specified as such by preceding it with the Public or Private keyword. Procedures are Public by default, if the Public keyword is not specified.

A Private procedure can only be called by all procedures in the same module and will not be visible or accessible to procedures of outside modules in the project. A Private procedure will also not appear in the Macros dialog box. A

Public procedure can be called by all procedures in the same module and also by all procedures of outside modules in the project. A Public procedure’s name will appear in the Macros dialog box and can be run therefrom.

Creating a Public procedure:

Sub calculateProcedure()

Public Sub calculateProcedure()

Function cubeRoot() As Double

Public Function cubeRoot() As Double

Creating a Private procedure:

Private Sub calculate()

Private Function cubeRoot() As Double


Placement of Macros / Sub procedures in appropriate Modules

Macros (viz. vba codes or sub-procedures) should reside in their appropriate modules or Excel will not be able to find and execute them. The Object Modules are used for Excel built-in event procedures and to create your own events. Object Modules in Excel are: ThisWorkbook module, Sheet modules (worksheets and chart sheets), UserForm modules and Class modules. General vba code in respect of events not associated with a particular object (like workbook or worksheet) are placed in the standard code module. A generally accepted practice is to place event procedures in the ThisWorkbook module, Sheet modules and UserForm modules, while placing other vba codes in Standard Code modules.

Refer Image 2 which shows the Modules in VBE.

Standard Code Modules:

These are also referred to as Code Modules or Modules, and there can be any number of these Modules (Module1, Module2, …) in a VBA project, wherein each Module can be used for covering a certain aspect of the project. Most vba codes and custom functions (viz. User Defined Functions referred to as UDFs) are placed in Standard Code Modules. Standard Code Modules are not used for event procedures linked and associated to a Workbook or Worksheet or UserForm or for Application events created in a Dedicated Class Module. In respect of events not associated with objects, such as OnTime method (automatically trigger a vba code at periodic intervals or at a specific day or time) and OnKey method (run a specific code on pressing a key or combination of keys), because these are not associated with a particular object like workbook or worksheet, their codes rest in the standard code module. Procedures in standard modules can be called from a procedure in an outside module just like you call a procedure located in the same module ie. without specifying the module of the called procedure.

Workbook module:

ThisWorkbook is the name of the module for the workbook and is used to place workbook events and Application Events. Workbook events are actions associated with the workbook, to trigger a VBA code or macro. Opening / closing / saving / activating / deactivating the workbook are examples of workbook events viz. with a workbook open event, you can run a sub-procedure automatically when a workbook is opened. Workbook events code must be placed in the code module for the ThisWorkbook object, and if they are placed in standard code modules, Excel will not be able to find and execute them. Though Application Events can be created in any object module, they are best placed in either an existing object module like ThisWorkbook or you can create a class module to handle them. Though general vba codes and procedures can also be placed in a workbook, but you will need to include ‘ThisWorkbook’ in the reference to call them (from outside the workbook module) viz. ThisWorkbook.ProcedureName.

Sheet Modules:

A sheet module has the same name as the worksheet’s code name with which it is associated viz. Sheet1, Sheet2, … In VBE, the code name of the selected worksheet appears to the right of (Name) in the Properties Window while the sheet name appears to the right of Name when you scroll down in the Properties Window. The code name can be changed only in the Properties window and not programmatically with code. Sheet module can be for a worksheet or a chart sheet  and is used to place worksheet and chart sheet events. Worksheet events are actions or occurrences associated with the worksheet, to trigger a VBA code or macro. Chart sheet events (ie. if a chart is a chart sheet) reside within its chart sheet and are enabled by default, similar to as worksheet events reside in their worksheet. But for using events for a chart object representing an embedded chart in a worksheet, a new class module has to be created.

To use the Excel provided worksheet event procedures, in the Visual Basic Editor after selecting the appropriate worksheet, select Worksheet from the Object box and then select a corresponding procedure from the Procedure box. After selecting the specific event, insert the vba code you want to be executed. Worksheet Event procedures are installed with the worksheet, ie. the code must be placed in the code module of the appropriate Sheet object and if they are placed in standard code modules, Excel will not be able to find and execute them. Instances of worksheet events are: selecting a cell or changing cell selection in a worksheet, making a change in the content of a worksheet cell, selecting or activating a worksheet, when a worksheet is calculated, and so on. For example, with the worskheet change event, a sub-procedure runs automatically when you change the contents of a worksheet cell. Though general vba codes and procedures can also be placed in a worksheet, but you will need to include the sheet module name in the reference to call them (from outside that sheet module) viz. Sheet3.ProcedureName.

UserForm Modules:

Event procedures for UserForm or its Controls are placed in the Code module of the appropriate UserForm. UserForm events are pre-determined events that occur for a particular UserForm and its Controls, examples include Initialize, Activate or Click. These are placed in the user form code module. You must double-click the body of a UserForm to view the UserForm Code module, referred to as a module ‘behind’ the UserForm, and then select UserForm or its Control from the Object box and then select a corresponding procedure from the Procedure box. After selecting the specific event, insert the vba code you want to be executed. Remember to set the Name property of controls before you start using event procedures for them, else you will need to change the procedure name corresponding to the control name given later. Only event procedures for the UserForm or its controls should be placed here. However, general vba codes and procedures can also be placed in a UserForm, but you will need to include the UserForm module name in the reference to call them (from outside that UserForm module) viz. UserForm1.ProcedureName.

Class Modules:

Class Modules are used to create new objects and you can create your own custom events in a class. A Custom Event is defined and declared in a Class Module using the Event keyword. An Event procedure can be created using the WithEvents keyword to declare an object variable of the Class Module type. Though Application Events can be created in any object module, they are best placed in either an existing object module like ThisWorkbook or by creating a class module to handle them. Also, for using events for a chart object representing an embedded chart in a worksheet, a new class module has to be created.

For a detailed understanding of Class Modules, refer section Custom Classes & Objects, Custom Events, using Class Modules in Excel VBA.


Calling Procedures

Subs and Functions can be called within each other. Calling a procedure refers to using or executing a procedure.

Calling Sub procedures in the Same Module

You can call sub-procedures either solely by their name or precede the name with the Call keyword.

Calling a sub named strGetName which does not receive arguments, which was declared as — Sub strGetName():

strGetName

Call strGetName

Calling a sub named strGetName which receives arguments, which was declared as — Sub strGetName(firstName As String, secondName As String):

Call strGetName(firstName, secondName)

strGetName firstName, secondName

Note that argument(s) must be enclosed within parentheses when using the Call keyword, and multiple arguments must omit the parentheses when the Call keyword is not used.

Calling Functions in the Same Module

Functions can be called in a manner similar to Subs and can also be used in an expression by their name. Functions can also be used directly in a worksheet, by entering/selecting the name of the function after typing an equal sign (refer Image 1 for using the Example 3 function in a worksheet). 

A function declared as — Function studentNames() As String — can be called as below:

studentNames

Call studentNames

A function which receives arguments and declared as — Function triple(i As Integer, j As Integer) As Long — can be called as below:

Call triple(i, j)

triple i, j

Using a Function in an expression: A function declared as — Function cubeRoot() As Double — can be called as below:

MsgBox cubeRoot * 2

Calling Procedures in Outside Modules

As explained above, Public procedures can be called by all procedures of outside modules. To do so, it is mostly required to specify the module that contains the called procedure. There are different ways to call procedures located in a workbook/ worksheet/ form module, standard module or a class module.

Calling Procedures located in a Workbook Module, Worksheet Module or Forms Module

If the called procedure is located in a Workbook Module, Worksheet Module or Forms Module, then you will need to specify the module while calling it from an outside module.

A sub named strGetName, which was declared as — Sub strGetName() — and located in the workbook module named ThisWorkbook, can be called by specifying — ThisWorkbook.strGetName — in the calling procedure located in an outside module.

A sub named strGetName, which was declared as — Sub strGetName() — and located in the worksheet module named Sheet2, can be called by specifying — Sheet2.strGetName — in the calling procedure located in an outside module.

A sub named strGetName, which was declared as — Sub strGetName() — and located in the UserForm named UserForm1, can be called by specifying — UserForm1.strGetName — in the calling procedure located in an outside module.

Calling Procedures located in Standard Modules

Procedures in standard modules can be called from a procedure in an outside module just like you call a procedure located in the same module ie. without specifying the module of the called procedure. A sub named strGetName, which was declared as — Sub strGetName() — and located in a standard module, can be called from a procedure in a worksheet module by using only its name ie. strGetName, or using the Call keyword ie. Call strGetName.

You might already be aware that procedures of same name are not allowed within the same module but procedures can have same names in separate modules. If both the standard modules (Module1 and Module2) have a procedure named strGetName, to call it from an outside module (say, from a standard module named Module3), you will need to specify the called procedure’s module viz. Module1.strGetName OR Module2.strGetName. However, if the calling procedure is located in Module2 and if you call the procedure named strGetName without specifying the module, then the procedure strGetName located in Module 2 will be called.

Calling Procedures located in Class Modules

In the calling procedure located in an outside module, you need to instantiate an instance of the class in which the called procedure is located. To do this, you create a variable and definine it as a reference to the class. Use this variable with the name of the called procedure located in the class module. For example, in the calling procedure use the statement — Dim iStudent As New clsStudent — to use a variable named iStudent and create an instance of the class named clsStudent. To call the Grade function located in the clsStudent object, use the variable with the function name — iStudent.Grade. If the Grade function receives an argument, then to call the Grade function — iStudent.Grade (argument).

For a detailed understanding of Class Modules, refer section Custom Classes & Objects, Custom Events, using Class Modules in Excel VBA.


Executing Procedures

Executing Function Procedures:

Executing a Function procedure: (i) the function can be called from another procedure viz. a sub procedure or function procedure; and (ii) the function can be used directly in the spreadsheet viz. in a worksheet formula by entering/selecting the name of the function after typing an equal sign. To see examples of Function procedures and how they are called, refer the headings «Function Procedures»  & «Calling Procedures» hereinabove.

Executing Event Procedures:

Events are actions performed, or occurrences, which trigger a VBA macro. An event procedure (ie. a vba code) is triggered when an event occurs such as opening / closing / saving / activating / deactivating the workbook, selecting a cell or changing cell selection in a worksheet, making a change in the content of a worksheet cell, selecting or activating a worksheet, when a worksheet is calculated, and so on.

Event procedures are attached to objects: An event procedure is a procedure with a standard name that runs on the occurrence of a corresponding event. The event procedure contains the user written customized code which gets executed when the specific Excel built-in event, such as worksheet change event, is triggered. Event Procedures are triggered by a predefined event and are installed within Excel having a standard & predetermined name viz. like the Worksheet change procedure is installed with the worksheet — «Private Sub Worksheet_Change(ByVal Target As Range)». An Event Procedure is automatically invoked when an object recognizes the occurrence of an event. Event procedures are attached to objects like Workbook, Worksheet, Charts, Application, UserForms or Controls. An event procedure for an object is a combination of the object’s name (as specified in the Name property), an underscore and the event name. To use the Excel provided event procedures, in the Visual Basic Editor select an object from the Object box and then select a corresponding procedure from the Procedure box. After selecting the specific event, insert the vba code you want to be executed.

Using ActiveX controls: ActiveX controls are used: 1) on worksheets — these can be used without or with vba code here; and 2) on UserForms, with vba code. ActiveX controls have event procedures that run on the occurrence of a corresponding event. These procedures are inserted in the code modules of the Worksheet or UserForm within which the controls are used. Some ActiveX controls can only be used on UserForms and not on worksheets. Note that you can assign macros to run directly from Forms controls, but you cannot assign a macro to run directly from ActiveX controls.

Using an ActiveX Control viz. Command Button, in a worksheet: On the Developer tab on the ribbon, click Insert in the Controls group, choose and click Command Button in ActiveX Controls and then click on your worksheet where you want to place the upper-left corner of the Command Button (you can move and resize later). To create an event procedure with the command button, in the code window in VBE, select the command button in the Object drop-down Box on the left, select the relevant event from the Procedure drop-down Box on the right, and insert the vba code. For example, if Click is selected in the Procedure drop-down Box after selecting CommandButton1 in the Object drop-down Box, the event procedure will be called CommandButton1_Click, and the vba code runs on clicking the Command Button.

Events not associated with objects, such as OnTime method (automatically trigger a vba code at periodic intervals or at a specific day or time) and OnKey method (run a specific code on pressing a key or combination of keys). Because these are not associated with a particular object like workbook or worksheet, their codes rest in the standard code module.

Executing Sub Procedures:

Run a Sub procedure (macro) using Macro dialog box, Shortcut key or in VBE:

Macro dialog box: Under the View tab on the ribbon, click Macros in the Macros group, click View Macros which will open the Macro dialog box. In the Macro dialog box, select the Macro name and click Run to execute the Sub/macro. You can also open the Macro dialog box by clicking on Macros in the Code group under the Developer tab on the ribbon. Yet another way is to use the key combination Alt+F8 which opens the Macro dialog box.

Shortcut key: Use the Shortcut key associated with the macro. For this you must already have assigned a Shortcut key to the macro which can be done both at the time when you begin recording a macro or later by selecting the sub / macro name in the macro list (in Macro dialog box) and clicking Options button.

Visual Basic Editor: 1) In the Visual Basic Editor, click within the sub procedure and press F5 (or click Run in the menu bar and then click Run Sub/Userform). 2) In the Visual Basic Editor, click Tools in the menu bar, then click Macros which opens the Macros dialog box. In the Macros dialog box, select the Macro name and click Run to execute the macro,

Obviously these methods are not very user friendly and you will not wish to automate an excel file with multiple macros and have users go through a «process» as described above, to select and run macros. A better way to run a macro would be to click on a button bearing a self-explanatory text «Calculate Bonus» appearing on the worksheet or clicking a Toolbar Button. We show how to assign a macro to an object, shape, graphic or control.

You can assign a sub / macro to:

A Form Control viz. Button: You can assign a macro to any Form control. On the Developer tab on the ribbon, click Insert in the Controls group, choose and click Button in Form Controls and then click on your worksheet where you want to place the the upper-left corner of the Button (you can move and resize later). Right click on the Button and select Assign Macro which opens the Assign Macro dialog box from where you can select and assign a macro to the Button.

The Quick Access Toolbar (Toolbar Button): Click the Office Button (top left of your excel window), click Excel Options which opens the Excel Options dialog box. Click Customize on the left, In the ‘Choose commands from’ drop-down box, select Macros, select a macro name on the left side list box and click ‘Add’ which adds it to the Quick Access Toolbar and the macro name now appears on the right side list box. To modify the macro button: select the macro name on the right side list box, click the Modify button at the bottom which opens the Modify Button dialog box from which you can select and modify the button which appears on the Quick Access Toolbar. Clicking this button on the Quick Access Toolbar will run the macro. Refer Image 3a which shows the Excel Options dialog box after selecting a macro; Image 3b shows (after clicking Add and Modify) the Modify Button dialog box wherein a new button is assigned for the macro; Image 3c (after clicking Ok twice) shows the macro button (i in blue circle) appearing on the Toolbar (we have assigned macro called macro1 in Sheet1 — Sheet1.macro1).

Any Object, Shape, Picture, Chart, Text Box, etc. inserted in the worksheet: Under the Insert tab on the ribbon, you can insert an Object, Shape, Picture, SmartArt graphic, Chart, Text Box, WordArt, etc. in the worksheet. Right click on the object, shape or graphic you have inserted, and select Assign Macro which opens the Assign Macro dialog box from where you can select and assign a macro to the Button.

Calling a Sub procedure from another Procedure:

Subs and Functions can be called within each other, as explained above under the heading «Calling Procedures». This means that a sub-procedure (or function) can be called from another procedure viz. a sub procedure or function procedure.

Assign multiple subs / macros:

You can assign multiple subs/macros to an object, graphic or control, by calling other sub procedures. Refer below example, in the sub procedure (CommandButton1_Click) which is executed on clicking a Command Button, two other sub procedures named macro1 and macro2 are called and executed. In this example macros are called using their names. You can view all macros by clicking Macros in the Macros group (under the View tab on the ribbon) and then selecting View Macros. Remember to type the macro names on separate lines while calling them.

Call sub procedures (macro1 & macro2 are located in standard code modules) using their names:

Private Sub CommandButton1_Click()

macro1
macro2

End Sub

Call sub procedures (using the Call method) where macro1 & macro2 are located in standard code modules and macro3 is in a worskheet module (in Sheet3) and macro4 is in the workbook module (ThisWorkbook), as shown below:

Private Sub CommandButton1_Click()

Call macro1
Call macro2
Call Sheet3.macro3
Call ThisWorkbook.macro4

End Sub

В отличии от языка VBScript, VBA процедуры классифицируются не на два типа (процедура-функция и процедура-подпрограмма), а четырех типов: процедура-функция, процедура-подпрограмма, процедура свойств и обработка событий. Также существуют некоторые дополнения в плане передачи параметров (по значению или по ссылке). Третьим моментом является область видимости – в VBA вызов процедуры может осуществляться как в пределах текущего модуля (макроса), так и за его пределами – во всех проектах. Все это обусловлено тем, что VBA – это не столько язык программирования, сколько программный пакет, с возможностью создания форм и проектов.

Давайте сначала кратко рассмотрим типы VBA процедур:

Подпрограммы – блоки кода заключенные в конструкцию Sub …. End Sub. Сама по себе подпрограмма не возвращает никакого значения, а просто выполняет прописанные в ней команды.

Функции – также блок кода, но прописанный в конструкцию Function … End Function. После выполнения функции возвращается определенное значение, доступ к которому можно получить через имя VBA функции.

Помимо этого, стоит упомянуть про обработку событий (нажатие кнопки клавиатуры или перемещение мыши) и доступ к объектам, но это отдельная тема.

VBA процедуры типа Sub – подпрограммы

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

Sub ИмяПодпрограмм([аргументы])
Операторы
[Exit Sub]
операторы
End Sub

После ключевого слова Sub следует имя подпрограммы, в круглых скобках можно указывать или не указывать аргументы. Аргументы – это переменные (параметры), значение которых может обрабатываться, аргументы разделяются запятыми. Конструкция Exit Sub также не является обязательной, она говорит  том, что нужно произвести выход из подпрограммы и продолжить выполнение кода, следующего после выражения End Sub.

Вызов VBA процедуры осуществляется с помощью ключевого слова call, например, Call MySub.

Давайте напишем простой пример: добавьте в проект новую форму и новый модуль. На поверхность формы добавьте два текстовых поля (TextBox), одну метку (Label) и одну кнопку (CommandButton). Создайте связь между формой и модулем, прописав в редакторе кода для модуля:

Sub SubModule()
    SubForm.Show
End Sub

Я назвал форму SubForm, а модуль – SubModule, за имя отвечает свойство Name.

vba вызов процедуры

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

'************************************
' Вычисление гипотенузы
'************************************
 
' процедура VBA принимает два параметра
Sub Hipotenuze(a, b)
Dim c
    ' Проверка, если значения равны нулю
    If TextBox1.Text = 0 Or TextBox2.Text = 0 Then
        a = 1: b = 1
    End If
    ' вычисление гипотенузы
    c = Sqr(a ^ 2 + b ^ 2)
    Label1.Caption = "Гипотенуза: " & c
End Sub
 
' Обработка нажатия на кнопку
Private Sub CommandButton1_Click()
Dim Ta, Tb
    Ta = TextBox1.Text
    Tb = TextBox2.Text
    ' vba вызов процедуры Hipotenuze
    Call Hipotenuze(Ta, Tb)
End Sub
 
' Настройка свойств при запуске формы
Private Sub UserForm_Initialize()
    Label1.Caption = ""
    Label1.FontSize = 15
    Label1.ForeColor = vbBlue
    CommandButton1.Caption = "Найти"
    TextBox1.Text = 5
    TextBox2.Text = 5
End Sub

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

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

Sub MySub (a As Integer, b As String) … End Sub

Дополнительные особенности:

Static – данное ключевое слово, прописанное перед ключевым словом Sub позволяет сохранять в памяти значения всех переменных после выполнения процедуры. Его мы рассматривали в с статье – переменные VBA.

ParamArray – данное ключевое слово позволяет передавать процедуре переменное количество параметров, оно может использоваться только для последнего элемента в списке аргументов.

Ключевое слово ParamArray

ParamArray нельзя использовать вместе со словами ByRef, ByVal или Optional, например:

'************************************
' Передача параметров
'************************************
 
' процедура VBA принимает два параметра
Sub MyArguments(a As Integer, ParamArray b())
Dim elem, s As String
    Label1.Caption = a
    For Each elem In b
        s = s & elem & " "
    Next
    Label2.Caption = s
End Sub
 
' Обработка нажатия на кнопку
Private Sub CommandButton1_Click()
    MyArguments 1, 5, 6, 100, "строка"
End Sub
 
' Настройка свойств при запуске формы
Private Sub UserForm_Initialize()
    Label1.Caption = ""
    Label1.FontSize = 15
    Label1.ForeColor = vbBlue
 
    Label2.Caption = ""
    Label2.FontSize = 15
    Label2.ForeColor = vbRed
    CommandButton1.Caption = "Вывести"
End Sub

Как видим, мы фактически с помощью ParamArray показываем, что передаем массив, для его обработки мы использовали оператор For …. Each. Тут мы передали при вызове VBA процедуры пять параметров, при этом, первый будет храниться в аргументе a, а остальные в аргументе b, который обрабатывается как массив.

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

VBA Sub и Function

Например:

'************************************
' Передача параметров
'************************************
 
Sub MyArguments(Optional a As Integer = 5, Optional b As String = " плюс ", Optional c As Integer = 10)
    Label1.Caption = a & b & c
End Sub
 
Private Sub CommandButton1_Click()
    MyArguments
End Sub
Private Sub CommandButton2_Click()
    MyArguments 100, " минус ", 50
End Sub
Private Sub CommandButton3_Click()
    MyArguments 20, , 30
End Sub
 
Private Sub UserForm_Initialize()
    Label1.Caption = ""
    Label1.FontSize = 15
    Label1.ForeColor = vbBlue
 
    CommandButton1.Caption = "Вариант 1"
    CommandButton2.Caption = "Вариант 2"
    CommandButton3.Caption = "Вариант 3"
End Sub

В данном примере на поверхности формы находится всего одна метка и три кнопки. Каждая из кнопок будет производить VBA вызов процедуры MyArguments с различными значениями.

Передача параметров по ссылке и по значению – по умолчанию, при вызове процедуры все параметры ей передаются по ссылке. Передача по ссылке – в простом варианте, это передача адреса по которому хранится значение. При передаче параметра по ссылке, передается не адрес, а копия значения.

Передача VBA параметров по ссылке и по значению

Что бы все стало понятно, рассмотрим следующий пример:

'************************************
' Передача параметров
'************************************
 
Sub MySub1()
Dim MyVar
    MyVar = 100
    Call MySumm1(MyVar)
    Label1.Caption = "Передача по ссылке " & MyVar
End Sub
 
Sub MySub2()
Dim MyVar
    MyVar = 100
    Call MySumm2(MyVar)
    Label2.Caption = "Передача по значению " & MyVar
End Sub
 
Sub MySumm1(ByRef a)
 a = a + 100
End Sub
Sub MySumm2(ByVal a)
 a = a + 100
End Sub
 
Private Sub CommandButton1_Click()
    MySub1
    MySub2
End Sub
 
Private Sub UserForm_Initialize()
    Label1.Caption = ""
    Label1.FontSize = 15
    Label1.ForeColor = vbBlue
 
    Label2.Caption = ""
    Label2.FontSize = 15
    Label2.ForeColor = vbRed
 
    CommandButton1.Caption = "Проверить"
End Sub

MySub1 – тут происходит объявление переменной MyVar и присвоение ей значения 100, далее в теле происходит вызов VBA процедуры MySumm1, ей в качестве параметры мы передаем значение переменной MyVar – 100. Сама процедура MySumm принимает значение по ссылке, на что указывает ключевое слово ByRef, к принятому значению прибавляется число 100. Стоит обратить внимание, что ByRef можно было и не писать. После VBA вызова процедуры MySumm1 происходит запись значения переменной MyVar в свойство Caption объекта Label1, в итоге, отобразится число 200.

MySub2 – аналог предыдущей процедуры, но тут происходит вызов MySumm2, в которой происходит передача параметров по значению, о чем говорит ключевое слово ByVal, в итоге, значение переменной MyVar не изменится.

VBA процедуры типа Function – функции

Пользовательским функциям языка VBA присущи практически те же правила, что и подпрограммам. Общая структура функции:

Function ИмяФункции ([аргументы]) [As ТипДанных]
Операторы
[Exit Function]
Операторы
[ИмяФункции=Выражение]
End Function

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

Function Summ(a As Integer, b As Integer) As Integer
    Summ = a + b
End Function
 
Private Sub CommandButton1_Click()
    Label1.Caption = "Сумма 10 и 20: " & Summ(10, 20)
End Sub
 
Private Sub UserForm_Initialize()
    Label1.Caption = ""
    Label1.FontSize = 15
    Label1.ForeColor = vbBlue
    CommandButton1.Caption = "Сумма"
End Sub

Return to VBA Code Examples

In this Article

  • Running a Sub Procedure from another Sub Procedure
  • Using the Call Statement
  • Calling a Sub with Arguments
  • Calling a Sub with Named Arguments

This tutorial will teach you how to call a sub procedure from within another sub procedure in VBA

It is very useful to write code that can be used repetitively, and called from multiple sub procedures in your project – it can save an enormous amount of time and makes the VBA code far more efficient.

Running a Sub Procedure from another Sub Procedure

Consider the 3 Sub Procedures below:

Sub TestRoutine()
   RunRoutine1
   RunRoutine2
End Sub
Sub RunRoutine1()
   MsgBox "Good Morning"
End Sub
Sub RunRoutine2()
   MsgBox "Today's date is " & Format(Date, "mm/dd/yyyy")
End Sub

If we run the Sub Procedure – TestRoutine – it will call RunRoutine1 and RunRoutine2 and 2 message boxes will appear.

vba run subs

There is no limit to the number of Sub Procedures you can call from another Sub Procedure.

Using the Call Statement

You can also use the Call Statement in front of the procedure name, to make your code easier to read.   However, it has no effect whatsoever on how the code is run or stored.

Sub TestRoutine() 
   Call RunRoutine1 
   Call RunRoutine2 
End Sub

vba run subs call

Calling a Sub with Arguments

It is also possible to call a sub with arguments

Sub TestRoutine() 
   RunRoutine1 ("Melanie")
   RunRoutine2 ("Have a lovely Day")
End Sub
Sub RunRoutine1(strName as String) 
   MsgBox "Good Morning " & " & strName
End Sub
Sub RunRoutine2(strMessage as String ) 
   MsgBox "Today's date is " & Format(Date, "mm/dd/yyyy")  & VbCrLf & strMessage
End Sub

vba run sub parameters

Calling a Sub with Named Arguments

If you name your arguments, you don’t have to pass them in the same order to your sub routines.

Sub TestRoutine() 
   RunRoutine1 strGreeting:="How are you?", strName:="Melanie"
End Sub
Sub RunRoutine1(strName as String, strGreeting as string  
MsgBox "Good Morning " & " & strName & vbCrLf & strGreeting 
End Sub

vba run sub multi parameters

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!

Понравилась статья? Поделить с друзьями:
  • Call out one word or two
  • Call of duty world at word
  • Call of duty one word
  • Call module in excel
  • Call me back in 5 minutes i new word in the aword app right now