Содержание
- CALL function
- Description
- Syntax
- Example
- Оператор Call
- Синтаксис
- Замечания
- Пример
- См. также
- Поддержка и обратная связь
- Excel VBA Calling modules
- 1 Answer 1
- VBA Excel. Вызов процедуры Sub из другой подпрограммы VBA
- Вызов процедур Sub в пределах одной книги
- Синтаксис вызова подпрограмм в пределах одной книги
- Вызов подпрограмм без аргументов в пределах одного модуля
- Вызов подпрограмм с аргументами в пределах одного модуля
- Вызов подпрограмм из разных модулей одной книги
- Вызываемая подпрограмма расположена в Стандартном модуле
- Вызываемая подпрограмма расположена в модуле книги, модуле листа, модуле формы
- Вызов процедур Sub из модулей разных книг
- Синтаксис метода Application.Run
- Полный адрес вызываемой процедуры
- Пример вызова подпрограмм из другой книги
- Заключение
CALL function
Important: Caution Incorrectly editing the registry may severely damage your operating system, requiring you to reinstall it. Microsoft cannot guarantee that problems resulting from editing the registry incorrectly can be resolved. Before editing the registry, back up any valuable data. For the most recent information about using and protecting your computer’s registry, see Microsoft Windows Help.
This article describes the formula syntax and usage of the CALL function in Microsoft Excel.
Note: The CALL function is not available in Excel for the web.
Description
Calls a procedure in a dynamic link library or code resource. There are two syntax forms of this function. Use syntax 1 only with a previously registered code resource, which uses arguments from the REGISTER function. Use syntax 2a or 2b to simultaneously register and call a code resource.
Important: This function is provided for advanced users only. If you use the CALL function incorrectly, you may cause errors that will require you to restart your computer. This function is only available from an Excel macro sheet.
Syntax
Used with REGISTER
Used alone (in Microsoft Excel for Windows)
Register_id is the value returned by a previously executed REGISTER or REGISTER.ID function.
The CALL function syntax has the following arguments:
Module_text Required. Quoted text specifying the name of the dynamic link library (DLL) that contains the procedure in Microsoft Excel for Windows.
Procedure Required. Text specifying the name of the function in the DLL in Microsoft Excel for Windows. You can also use the ordinal value of the function from the EXPORTS statement in the module-definition file (.DEF). The ordinal value must not be in the form of text.
Type_text Required. Text specifying the data type of the return value and the data types of all arguments to the DLL or code resource. The first letter of type_text specifies the return value. The codes you use for type_text are described in detail in Using the CALL and REGISTER functions. For stand-alone DLLs or code resources (XLLs), you can omit this argument.
Argument1. Optional. The arguments to be passed to the procedure.
Example
The following macro formula registers the GetTickCount function from 32-bit Microsoft Windows. GetTickCount returns the number of milliseconds that have elapsed since Microsoft Windows was started.
Assuming that this REGISTER function is in cell A5, after your macro registers GetTickCount, you can use the CALL function to return the number of milliseconds that have elapsed:
Источник
Оператор Call
Передает управление процедуреSub, процедуре функции или процедуре динамической библиотеки (DLL).
Синтаксис
[ Позвонить ] name [ argumentlist ]
Синтаксис оператора Call состоит из следующих частей:
Part | Описание |
---|---|
Звонок | Необязательный элемент; ключевое слово. Если указан, следует заключить элемент список_аргументов в скобки.
Пример: Call MyProc(0) |
name | Обязательно. Имя вызываемой процедуры. |
список аргументов | Необязательный параметр. Список с разделителями-запятыми переменных, массивов или выражений, передаваемых процедуре. Компоненты список_аргументов могут включать ключевые слова ByVal или ByRef для описания способа, с помощью которого аргументы обрабатываются вызванной процедурой.
Однако ByVal и ByRef могут использоваться с ключевым словом Call только при вызове процедуры DLL. На компьютерах Macintosh ByVal и ByRef могут использоваться с ключевым словом Call при вызове ресурса кода Macintosh. |
Замечания
Ключевое слово Call не требуется обязательно использовать при вызове процедуры. Однако если ключевое слово Call используется для вызова процедуры, требующей задания аргументов, элемент список_аргументов должен быть заключен в скобки. Если ключевое слово Call будет пропущено, необходимо также убрать и скобки вокруг элемента список_аргументов. Если используется синтаксис Call для вызова любой внутренней либо определяемой пользователем функции, значение, возвращаемое этой функцией, отбрасывается.
Чтобы передать процедуре целый массив, используйте имя этого массива, после которого следует записать пустые скобки.
Пример
В этом примере показано, как оператор Call используется для передачи управления процедуре Sub , встроенной функции и процедуре динамической библиотеки (DLL). Библиотеки DLL не используются в Macintosh.
См. также
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Excel VBA Calling modules
So I have put together this code, but I am having trouble running it. I tried calling on the sub routines, but nothing was happening. I am stuck on how to call the modules I have created. I have also created a MainMenu() sub and I am wondering if that was maybe a mistake and I should have run my MainMenu from sheet1. Maybe someone has a better idea.
My original plan was to create a commandbutton where if clicked module1, which contains the MainMenu() would run.
Within module1 there is a loop that runs and calls the other three modules
I can not figure out where I am going wrong exactly. if anyone sees something I am missing please let me know. I appreciate any help
1 Answer 1
This is all the code we needed to see:
You don’t «call» modules, modules are containers for procedures and functions. What you «call», is procedures and functions. So if you have Sub DoSomething() in Module5 , you can invoke it like this:
Or, if there’s no DoSomething anywhere else:
Just like you would invoke VBA.Interaction.MsgBox like MsgBox «Hello!» . Note that you don’t need to have a Call keyword anywhere for it to work.
Your Module2.SourceApprove procedure has parameters. So you can’t just do SourceApprove or Module2.SourceApprove , VBA will complain that a parameter is not optional.
So you supply the parameters in a comma-separated list of values:
These could be variables, too.
Consider using meaningful names for your parameters — that way IntelliSense will help you know what values to provide. You can (should) also specify a type for the parameters, so that «first» can’t be provided as a value for a parameter that requires a number.
Источник
VBA Excel. Вызов процедуры Sub из другой подпрограммы VBA
Вызов процедур Sub (подпрограмм) из кода других процедур, расположенных в одном или разных модулях, в одной или разных книгах Excel (проектах VBA), с аргументами или без. Примеры.
Вызов процедур Sub в пределах одной книги
Вызов подпрограммы из кода другой процедуры Sub, расположенной в том же модуле или другом модуле одной рабочей книги (проекта VBA) осуществляется с помощью ключевого слова Call или без него по имени подпрограммы. Вызывающая процедура Sub может быть любой видимости, как Public, так и Private, а вызываемая, если расположена в том же модуле, может быть любой видимости, но если расположена в другом модуле, должна быть объявлена как Public.
Синтаксис вызова подпрограмм в пределах одной книги
[ Call ] ИмяПроцедуры [ (Аргументы) ]
- Call — необязательное ключевое слово;
- ИмяПроцедуры — обязательный компонент, имя вызываемой подпрограммы;
- Аргументы — необязательный компонент, список аргументов вызываемой процедуры Sub, разделенных запятой.
Вызов подпрограмм без аргументов в пределах одного модуля
Скобки рядом с именами вызываемых подпрограмм без аргументов не ставятся:
Вы можете скопировать приведенный код в свой модуль и посмотреть, запустив процедуру test1, как она последовательно запускает процедуры test2 и test3.
Вызов подпрограмм с аргументами в пределах одного модуля
При вызове процедур Sub с аргументами и ключевым словом Call, аргументы заключаются в скобки, без ключевого слова Call — аргументы не заключаются в скобки:
Вы можете разместить этот код в своем модуле и протестировать его.
Вызов подпрограмм из разных модулей одной книги
Правила, касающиеся использования оператора Call и заключения аргументов в скобки, верны и для вызова процедур Sub, находящихся в разных модулях. Единственным отличием является необходимость вместе с именем вызываемой подпрограммы указывать место ее расположения. Место расположения и имя подпрограммы разделяются точкой.
Вызываемая подпрограмма расположена в Стандартном модуле
- ИмяМодуля — уникальное имя стандартного модуля, отображаемое в проводнике проекта VBA.
Неуникальное имя процедуры возникает, когда создаются процедуры с одним именем в разных модулях. Если есть вероятность дублирования в дальнейшем имени подпрограммы и лишения ее уникальности, то лучше сразу вызывать ее с указанием имени стандартного модуля.
Вызываемая подпрограмма расположена в модуле книги, модуле листа, модуле формы
- ЭтаКнига — так и пишется, указывает на текущую книгу в которой расположены вызывающая и вызываемая подпрограммы.
- ИмяЛиста — уникальное имя листа, которое в проводнике проекта VBA указано без скобок (по умолчанию: Лист1, Лист2, Лист3 и т.д.).
- Имя ярлычка листа — дублирующее имя листа, которое в проводнике проекта VBA указано в скобках.
- ИмяФормы — уникальное имя пользовательской формы, отображаемое в проводнике проекта VBA.
Вызов процедур Sub из модулей разных книг
Если вызываемая подпрограмма расположена в другой книге, она должна быть объявлена как Public, а книга открыта. Запустить такую процедуру Sub можно с помощью метода Application.Run (протестировано в Excel 2016).
Синтаксис метода Application.Run
Application.Run «ИмяКниги!ИмяМодуля.ИмяПроцедуры», Арг1, Арг2, …, Арг30
- ИмяКниги!ИмяМодуля.ИмяПроцедуры — обязательный компонент, полный адрес подпрограммы, заключен в двойные кавычки.
- ИмяКниги — имя рабочей книги Excel с расширением, в которой находится вызываемая подпрограмма, если имя содержит пробелы, оно заключается в одинарные кавычки — апострофы (‘Имя Книги’).
- ИмяМодуля — имя модуля для стандартного модуля (для уникальных имен вызываемых подпрограмм может не указываться), имя листа для модуля листа, словосочетание «ЭтаКнига» (без кавычек) для модуля книги.
- ИмяПроцедуры — имя вызываемой процедуры Sub.
- Арг1, Арг2, …, Арг30 — необязательные компоненты, аргументы вызываемой подпрограммы, максимальное количество которых ограничено 30 элементами.
Полный адрес вызываемой процедуры заключен в двойные кавычки, отделен от аргументов и аргументы друг от друга запятыми.
Полный адрес вызываемой процедуры
Может показаться сложным составить полный адрес вызываемой подпрограммы, но на самом деле все очень просто — Excel уже сделал это за нас.
Список макросов во всех открытых книгах
2. Найдите в списке вызываемую подпрограмму и кликните по ней. Ее полный адрес отобразится в поле «Имя макроса».
3. Скопируйте полное имя вызываемой процедуры Sub и вставьте ее в метод Application.Run, заключив в двойные кавычки.
Один нюанс: в окне «Макрос» не отображаются процедуры с аргументами. Чтобы отобразить такую процедуру, закомментируйте аргументы, а после копирования и вставки раскомментируйте их.
Стоит не забывать о том, что если книга с вызываемой подпрограммой будет переименована, то полное имя вызываемой процедуры Sub изменится и везде, где оно присутствует в коде, его необходимо будет отредактировать.
Пример вызова подпрограмм из другой книги
Допустим, у нас есть рабочая книга Excel под именем «Книга1.xlsm» (или «Книга1.xls» в ранних версиях программы). В ней находятся вызываемые из другой книги процедуры Sub, перечисленные ниже.
В стандартном модуле «Module1»:
В модуле листа «Лист1»:
В модуле книги «ЭтаКнига»:
Для последовательного запуска этих подпрограмм можно вставить в любой модуль другой книги Excel следующую процедуру:
Во второй строке кода пропущено имя стандартного модуля, так как имя подпрограммы оказалось уникальным, а в следующей строке этот же код продублирован, для примера, с именем модуля. В пятой строке — пример запуска процедуры Sub с двумя аргументами.
И еще раз напомню, что имя книги с пробелами заключается в одинарные кавычки (апострофы):
Если у вас есть процедуры, которые часто вызываются из других книг, поместите их в Личную книгу макросов, и они всегда будут доступны.
Заключение
В этой статье не рассмотрено добавление ссылок из одного проекта VBA на другой, которые позволяют работать с модулями и процедурами, находящимися в другом проекте так, как с находящимися в текущем. Причем книга, с которой установлена связь, может быть закрыта. Я предпочитаю работать с Личной книгой макросов, а при попытке, из любопытства, установить связь между двумя книгами, программа Excel, почему-то, отказала мне в этом и эксперименты закончились.
Если хотите поэкспериментировать со связанными книгами, откройте проект VBA, из которого надо установить связь с другой книгой, и выберите в главном меню «Tools» — «References…». В открывшемся окне «References — VBAProject» все открытые книги будут отображены одним словом — «VBAProject». Выделяйте по очереди строки с этим словом и внизу, в информационной рамке, смотрите, какой книге этот проект принадлежит. Поставьте галочку рядом с выбранным проектом и нажмите кнопку «OK». Если книга, с проектом которой устанавливается связь, закрыта, ее не будет в списке. В этом случае, нажмите на кнопку «Browse…», найдите, выбрав расширение, нужную книгу и откройте ее в проводнике. Связь будет установлена, и процедуры из связанных книг будут вызываться по имени с ключевым словом Call или без него, как будто они расположены в одной книге.
Источник
How can I call a module written in Excel by clicking on an ActiveX control in a worksheet?
Excellll
12.5k11 gold badges50 silver badges78 bronze badges
asked May 18, 2012 at 12:39
It’s not entirely clear what you’re asking, but I understand this to be your problem:
You have an ActiveX Control that runs on a click event. The VBA for this is only called by the button click and cannot be called from any other Sub, but you would like to be able to call this code from another module.
I don’t believe you can do that, but there is a better approach to the problem. Place the code for your ActiveX control in a new Sub in a module. Then replace the code for the button click event with the following:
Private Sub CommandButton1_Click()
Call NewSub
End Sub
Where NewSub
is the name of your new Sub. This should allow you to do what you wanted.
answered May 18, 2012 at 16:41
ExcellllExcellll
12.5k11 gold badges50 silver badges78 bronze badges
The code for an ActiveX control, such as a button_click on a worksheet, may be called from other subs, even on other modules. Simply use the keyword «Public» to describe the ActiveX control sub instead of «Private». Then call the sub with a statement such as Call Sheets(mySheetName).myButtonName_Click
.
answered Sep 4, 2013 at 20:49
To call subroutine located in ThisWorkbook from SHeet1:
Do that:
Call ThisWorkbook.ParseText
Where definition:
Public Sub ParseText()
answered Apr 27, 2018 at 11:40
Excel for Microsoft 365 Excel for Microsoft 365 for Mac Excel for the web Excel 2021 Excel 2021 for Mac Excel 2019 Excel 2019 for Mac Excel 2016 Excel 2016 for Mac Excel 2013 Excel for iPad Excel for iPhone Excel for Android tablets Excel 2010 Excel 2007 Excel for Mac 2011 Excel for Android phones Excel Starter 2010 More…Less
Important:
Caution Incorrectly editing the registry may severely damage your operating system, requiring you to reinstall it. Microsoft cannot guarantee that problems resulting from editing the registry incorrectly can be resolved. Before editing the registry, back up any valuable data. For the most recent information about using and protecting your computer’s registry, see Microsoft Windows Help.
This article describes the formula syntax and usage of the CALL function in Microsoft Excel.
Note: The CALL function is not available in Excel for the web.
Description
Calls a procedure in a dynamic link library or code resource. There are two syntax forms of this function. Use syntax 1 only with a previously registered code resource, which uses arguments from the REGISTER function. Use syntax 2a or 2b to simultaneously register and call a code resource.
Important: This function is provided for advanced users only. If you use the CALL function incorrectly, you may cause errors that will require you to restart your computer. This function is only available from an Excel macro sheet.
Syntax
Syntax 1
Used with REGISTER
CALL(register_id,[argument1],…)
Syntax 2
Used alone (in Microsoft Excel for Windows)
Register_id is the value returned by a previously executed REGISTER or REGISTER.ID function.
CALL(module_text,procedure,type_text,[argument1],…])
The CALL function syntax has the following arguments:
-
Module_text Required. Quoted text specifying the name of the dynamic link library (DLL) that contains the procedure in Microsoft Excel for Windows.
-
Procedure Required. Text specifying the name of the function in the DLL in Microsoft Excel for Windows. You can also use the ordinal value of the function from the EXPORTS statement in the module-definition file (.DEF). The ordinal value must not be in the form of text.
-
Type_text Required. Text specifying the data type of the return value and the data types of all arguments to the DLL or code resource. The first letter of type_text specifies the return value. The codes you use for type_text are described in detail in Using the CALL and REGISTER functions. For stand-alone DLLs or code resources (XLLs), you can omit this argument.
-
Argument1,… Optional. The arguments to be passed to the procedure.
Example
The following macro formula registers the GetTickCount function from 32-bit Microsoft Windows. GetTickCount returns the number of milliseconds that have elapsed since Microsoft Windows was started.
REGISTER(«Kernel32″,»GetTickCount»,»J»)
Assuming that this REGISTER function is in cell A5, after your macro registers GetTickCount, you can use the CALL function to return the number of milliseconds that have elapsed:
CALL(A5)
Need more help?
Want more options?
Explore subscription benefits, browse training courses, learn how to secure your device, and more.
Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.
I have a simular struction on one of my vba-scripts, and it goes like this.
Private Sub CommandButton1_Click()
Call GetData1
End Sub
and in my module2, it looks like this
Sub GetData1()
'my code
Dim IE As Object
Dim dd As Variant
Set IE = GetObject("new:{D5E8041D-920F-45e9-B8FB-B1DEB82C6E5E}")
IE.Visible = False
IE.Navigate "https://www.avanza.se/aktier/om-aktien.html/5247/investor-b"
Application.StatusBar = "Loading, Please wait..."
IEWait IE
Application.StatusBar = "Searching for value. Please wait..."
dd = IE.Document.getElementsByClassName("lastPrice SText bold")(0).innerText
Range("G7").Value = dd
End Sub
Maybe a bit to much, but I just wanted you to understand the structure of the code I’m using.
So everytime I click the buttom «CommandButton1»
This code above will execute, but in your case everytime you call the function main_try() , you should, as pointed out above, call on the functions in the modules, not the module itself.
Hoped it helped, best regards
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
Вызов процедур 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
- ИмяКниги!ИмяМодуля.ИмяПроцедуры — обязательный компонент, полный адрес подпрограммы, заключен в двойные кавычки.
- ИмяКниги — имя рабочей книги Excel с расширением, в которой находится вызываемая подпрограмма, если имя содержит пробелы, оно заключается в одинарные кавычки — апострофы (‘Имя Книги’).
- ИмяМодуля — имя модуля для стандартного модуля (для уникальных имен вызываемых подпрограмм может не указываться), имя листа для модуля листа, словосочетание «ЭтаКнига» (без кавычек) для модуля книги.
- ИмяПроцедуры — имя вызываемой процедуры Sub.
- Арг1, Арг2, …, Арг30 — необязательные компоненты, аргументы вызываемой подпрограммы, максимальное количество которых ограничено 30 элементами.
Полный адрес вызываемой процедуры заключен в двойные кавычки, отделен от аргументов и аргументы друг от друга запятыми.
Полный адрес вызываемой процедуры
Может показаться сложным составить полный адрес вызываемой подпрограммы, но на самом деле все очень просто — Excel уже сделал это за нас.
1. Откройте окно со списком макросов.
Список макросов во всех открытых книгах
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 или без него, как будто они расположены в одной книге.
Open your workbook in Excel. Press Alt + F11 to open Visual Basic Editor (VBE). Right-click on your workbook name in the “Project-VBAProject” pane (at the top left corner of the editor window) and select Insert -> Module from the context menu. Copy the VBA code (from a web-page etc.)
Contents
- 1 How do I run a macro script in Excel?
- 2 Where is module on Excel?
- 3 Where are Excel modules located?
- 4 How do you run a script in Excel?
- 5 How do I run a macro line by line?
- 6 How do I add a module to Excel?
- 7 How do I automatically run a VBA module in Excel?
- 8 What is an Excel module?
- 9 What is a module code?
- 10 What is a module sheet?
- 11 How do I create a VBA module in Excel?
- 12 How do you automate something in Excel?
- 13 How do I turn on automated in Excel?
- 14 What is VBA in Excel?
- 15 How do you run a macro step by step in Excel?
- 16 How do I run a VBA function in Excel?
- 17 What are the steps to run a macro code?
- 18 Why can’t I run a macro in Excel?
- 19 How do I run all macros at once?
- 20 How do I save a module in Excel?
How do I run a macro script in Excel?
Run a macro from the Developer tab
- Open the workbook that contains the macro.
- On the Developer tab, in the Code group, click Macros.
- In the Macro name box, click the macro that you want to run, and press the Run button.
- You also have other choices: Options – Add a shortcut key, or a macro description.
Where is module on Excel?
To view a module, just double click on its icon in the Project Explorer window in the VBA Editor. Standard modules are located under the Modules folder, Object modules are located under the Microsoft Excel Objects folder, and Class modules are located under the Classes folder.
Where are Excel modules located?
The modules are located in the Modules folder within the workbook. Sheet Modules – Each sheet in the workbook has a sheet object in the Microsoft Excel Objects folder. Double-clicking the sheet object opens its code module where we can add event procedures (macros).
How do you run a script in Excel?
Getting started
- First, select the Automate tab on the ribbon.
- To create a new Office Script, press the Record Actions button, then start taking the steps you want to automate.
- When you start recording a new Office Script, you’ll see a Record Actions task pane open on the right.
How do I run a macro line by line?
F8 is the key! In the visual basic editor, place your cursor inside of the macro and hit F8. This will run the first line of your code. Hit F8 to run each additional line, or F5 to resume without stopping.
How do I add a module to Excel?
Press Alt+F11 to open the Visual Basic Editor (on the Mac, press FN+ALT+F11), and then click Insert > Module. A new module window appears on the right-hand side of the Visual Basic Editor.
How do I automatically run a VBA module in Excel?
Instructions:
- Open an excel workbook.
- Press Alt+F11 to open VBA Editor.
- Insert a New Module from Insert Menu.
- Copy the above code and Paste in the code window.
- Save the file as macro enabled workbook.
- Open the workbook to test it, it will Run a Macro Automatically. You should see a message box as shown above.
What is an Excel module?
Workbook And Sheet Modules are special modules tied directly to the Workbook object and to each Sheet object. The module for the workbook is called ThisWorkbook, and each Sheet module has the same name as the sheet that it is part of. These modules should contain the event procedures for the object, and that’s all.
What is a module code?
Each module and each course is designated by a specific code. The first four digits represent the respective institute and the department or study field (i.e. of the responsible person / course instructor). The next three digits correlate to the type of module and the term, as well as the courses.
What is a module sheet?
1. A module is simply a place to put your code. You can just see it as a sheet of paper where you can write something. In Excel you can put your code in a module, or “behind” a worksheet (what you call a modulesheet). A module is always added manually BY YOU.
How do I create a VBA module in Excel?
To create a new module:
- On the Tools menu, click Macro > Visual Basic Editor.
- In the Visual Basic Editor, on the Insert menu, click Module.
- In the Module editing window, paste the VBA code that you want to use.
- On the File menu, click Save Global.
How do you automate something in Excel?
To automate a repetitive task, you can record a macro with the Macro Recorder in Microsoft Excel. Imagine you have dates in random formats and you want to apply a single format to all of them. A macro can do that for you. You can record a macro applying the format you want, and then replay the macro whenever needed.
How do I turn on automated in Excel?
Click the Microsoft Office Button, and then click Excel Options. Click Add-Ins. Under Manage, click Excel Add ins, and then click Go. In the Add-Ins dialog box, click Automation.
What is VBA in Excel?
VBA stands for Visual Basic for Applications. Excel VBA is Microsoft’s programming language for Excel.and all the other Microsoft Office programs, like Word and PowerPoint. The Office suite programs all share a common programming language.
How do you run a macro step by step in Excel?
Right-click the macro in the Navigation Pane, and then click Design View. On the Design tab, in the Tools group, click Single Step. Click Run. If the macro is a new or edited macro, you will be prompted to save the macro before you can run it.
How do I run a VBA function in Excel?
Single Step
- Empty the range A1:E2.
- Press F8 four times.
- Press F8 two more times.
- Single step through the rest of the code to see how Excel VBA enters the other numbers.
- Click on the green arrow to execute the macro until the breakpoint.
- Only part of the macro (for i = 1) has been executed.
What are the steps to run a macro code?
Here are the steps:
- Go to the Developer Tab –> Code –> Macros.
- The Macros dialogue box lists all the macros in the workbook. Select the one that you want to run.
- Click Run.
Why can’t I run a macro in Excel?
Click the File tab, and then click Options at the very bottom of the left bar. On the left-side pane, select Trust Center, and then click Trust Center Settings… . In the Trust Center dialog box, click Macro Settings on the left, select Enable all macros and click OK.
How do I run all macros at once?
Just type the word Call then space, then type the name of the macro to be called (run). The example below shows how to call Macro2 from Macro1. It’s important to note that the two macros DO NOT run at the same time. Once the Call line is hit, Macro2 will be run completely to the end.
How do I save a module in Excel?
Saving a Module (Exporting)
- On the File menu, click Export File….
- Click the right mouse button, and click Export File….
- Press Ctrl + E keys on the keyboard.
VBA Macro is for developers. In Excel, macro is a piece of code written in VBA and VBA is Microsoft’s programming language, it stands for Visual Basic for Applications. The module is a file with a .bcf extension that stores the code written in the Visual Basic for Applications editor. Let’s learn, how to run a code from a module in excel VBA.
Run a code from the Module in Excel VBA
Step 1: Go to Developer Tab, under the code section you will find Visual basic. Now click on Visual Basic.
Step 2: Microsoft Visual Basic for Applications(VBA) dialogue box appears. In the Menu bar, go to Insert Tab, and click on Module.
Step 3: A Module named Module1 is created under the VBA project.
Step 4: Write the code you want to run in Microsoft excel. For example, a message box will appear stating “Learning geeks for geeks”.
Step 5: In the Tools bar. Click on the run button. You can also press F4(Fn + f4) on your keyboard to run the module code.
Step 6: The code pauses and the Microsoft VBA editor minimizes and a message box appears in the MS Excel worksheet. Click Ok. The code resumes and the Microsoft VBA editor maximizes again.
Scope of Module in VBA
The scope of the module in VBA is workbook level. You can use the written modules in different worksheets. You have created a module named module1 in shee1 above. A sub-procedure named geeksforgeeks() is also created. We will use this procedure to check the scope of a module in VBA. Following are the steps:
Step 1: Click on the plus and a new worksheet named sheet2 is created.
Step 2: Go to the Developer tab, and click on Macros.
Step 3: A dialogue box named Macro appears. In the macro name, you will find a procedure name geeksforgeeks(). This was the procedure that we wrote in sheet1 of this workbook. This proved that the scope of the module is workbook level. Select it, and click on Run.
Step 4: The code written in the module1 sub procedure gets executed. A dialogue box appears.