Vba excel вызов 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

  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 или без него, как будто они расположены в одной книге.

Содержание

  1. Встроенные функции VBA
  2. Пользовательские процедуры «Function» и «Sub» в VBA
  3. Аргументы
  4. Необязательные аргументы
  5. Передача аргументов по значению и по ссылке
  6. VBA процедура «Function»
  7. Пример VBA процедуры «Function»: Выполняем математическую операцию с 3 числами
  8. Вызов VBA процедуры «Function»
  9. Вызов VBA процедуры «Function» из другой процедуры
  10. Вызов VBA процедуры «Function» из рабочего листа
  11. VBA процедура «Sub»
  12. VBA процедура «Sub»: Пример 1. Выравнивание по центру и изменение размера шрифта в выделенном диапазоне ячеек
  13. VBA процедура «Sub»: Пример 2. Выравнивание по центру и применение полужирного начертания к шрифту в выделенном диапазоне ячеек
  14. Вызов процедуры «Sub» в Excel VBA
  15. Вызов VBA процедуры «Sub» из другой процедуры
  16. Вызов VBA процедуры «Sub» из рабочего листа
  17. Область действия процедуры VBA
  18. Ранний выход из VBA процедур «Function» и «Sub»

Встроенные функции VBA

Перед тем, как приступить к созданию собственных функций VBA, полезно знать, что Excel VBA располагает обширной коллекцией готовых встроенных функций, которые можно использовать при написании кода.

Список этих функций можно посмотреть в редакторе VBA:

  • Откройте рабочую книгу Excel и запустите редактор VBA (нажмите для этого Alt+F11), и затем нажмите F2.
  • В выпадающем списке в верхней левой части экрана выберите библиотеку VBA.
  • Появится список встроенных классов и функций VBA. Кликните мышью по имени функции, чтобы внизу окна отобразилось её краткое описание. Нажатие F1 откроет страницу онлайн-справки по этой функции.

Кроме того, полный список встроенных функций VBA с примерами можно найти на сайте Visual Basic Developer Centre.

Пользовательские процедуры «Function» и «Sub» в VBA

В Excel Visual Basic набор команд, выполняющий определённую задачу, помещается в процедуру Function (Функция) или Sub (Подпрограмма). Главное отличие между процедурами Function и Sub состоит в том, что процедура Function возвращает результат, процедура Sub – нет.

Поэтому, если требуется выполнить действия и получить какой-то результат (например, просуммировать несколько чисел), то обычно используется процедура Function, а для того, чтобы просто выполнить какие-то действия (например, изменить форматирование группы ячеек), нужно выбрать процедуру Sub.

Аргументы

При помощи аргументов процедурам VBA могут быть переданы различные данные. Список аргументов указывается при объявлении процедуры. К примеру, процедура Sub в VBA добавляет заданное целое число (Integer) в каждую ячейку в выделенном диапазоне. Передать процедуре это число можно при помощи аргумента, вот так:

Sub AddToCells(i As Integer)

...

End Sub

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

Необязательные аргументы

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

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

Sub AddToCells(Optional i As Integer = 0)

В таком случае целочисленный аргумент i по умолчанию будет равен 0.

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

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

Аргументы в VBA могут быть переданы процедуре двумя способами:

  • ByVal – передача аргумента по значению. Это значит, что процедуре передаётся только значение (то есть, копия аргумента), и, следовательно, любые изменения, сделанные с аргументом внутри процедуры, будут потеряны при выходе из неё.
  • ByRef – передача аргумента по ссылке. То есть процедуре передаётся фактический адрес размещения аргумента в памяти. Любые изменения, сделанные с аргументом внутри процедуры, будут сохранены при выходе из процедуры.

При помощи ключевых слов ByVal или ByRef в объявлении процедуры можно задать, каким именно способом аргумент передаётся процедуре. Ниже это показано на примерах:

Sub AddToCells(ByVal i As Integer)

...

End Sub
В этом случае целочисленный аргумент i передан по значению. После выхода из процедуры Sub все сделанные с i изменения будут утрачены.
Sub AddToCells(ByRef i As Integer)

...

End Sub
В этом случае целочисленный аргумент i передан по ссылке. После выхода из процедуры Sub все сделанные с i изменения будут сохранены в переменной, которая была передана процедуре Sub.

Помните, что аргументы в VBA по умолчанию передаются по ссылке. Иначе говоря, если не использованы ключевые слова ByVal или ByRef, то аргумент будет передан по ссылке.

Перед тем как продолжить изучение процедур Function и Sub более подробно, будет полезным ещё раз взглянуть на особенности и отличия этих двух типов процедур. Далее приведены краткие обсуждения процедур VBA Function и Sub и показаны простые примеры.

VBA процедура «Function»

Редактор VBA распознаёт процедуру Function, когда встречает группу команд, заключённую между вот такими открывающим и закрывающим операторами:

Function

...

End Function

Как упоминалось ранее, процедура Function в VBA (в отличие от Sub), возвращает значение. Для возвращаемых значений действуют следующие правила:

  • Тип данных возвращаемого значения должен быть объявлен в заголовке процедуры Function.
  • Переменная, которая содержит возвращаемое значение, должна быть названа так же, как и процедура Function. Эту переменную не нужно объявлять отдельно, так как она всегда существует как неотъемлемая часть процедуры Function.

Это отлично проиллюстрировано в следующем примере.

Пример VBA процедуры «Function»: Выполняем математическую операцию с 3 числами

Ниже приведён пример кода VBA процедуры Function, которая получает три аргумента типа Double (числа с плавающей точкой двойной точности). В результате процедура возвращает ещё одно число типа Double, равное сумме первых двух аргументов минус третий аргумент:

Function SumMinus(dNum1 As Double, dNum2 As Double, dNum3 As Double) As Double

   SumMinus = dNum1 + dNum2 - dNum3

End Function

Эта очень простая VBA процедура Function иллюстрирует, как данные передаются процедуре через аргументы. Можно увидеть, что тип данных, возвращаемых процедурой, определён как Double (об этом говорят слова As Double после списка аргументов). Также данный пример показывает, как результат процедуры Function сохраняется в переменной с именем, совпадающим с именем процедуры.

Вызов VBA процедуры «Function»

Если рассмотренная выше простая процедура Function вставлена в модуль в редакторе Visual Basic, то она может быть вызвана из других процедур VBA или использована на рабочем листе в книге Excel.

Вызов VBA процедуры «Function» из другой процедуры

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

Sub main()

   Dim total as Double
   total = SumMinus(5, 4, 3)

End Sub

Вызов VBA процедуры «Function» из рабочего листа

VBA процедуру Function можно вызвать из рабочего листа Excel таким же образом, как любую другую встроенную функцию Excel. Следовательно, созданную в предыдущем примере процедуру FunctionSumMinus можно вызвать, введя в ячейку рабочего листа вот такое выражение:

=SumMinus(10, 5, 2)

VBA процедура «Sub»

Редактор VBA понимает, что перед ним процедура Sub, когда встречает группу команд, заключённую между вот такими открывающим и закрывающим операторами:

VBA процедура «Sub»: Пример 1. Выравнивание по центру и изменение размера шрифта в выделенном диапазоне ячеек

Рассмотрим пример простой VBA процедуры Sub, задача которой – изменить форматирование выделенного диапазона ячеек. В ячейках устанавливается выравнивание по центру (и по вертикали, и по горизонтали) и размер шрифта изменяется на заданный пользователем:

Sub Format_Centered_And_Sized(Optional iFontSize As Integer = 10)

   Selection.HorizontalAlignment = xlCenter
   Selection.VerticalAlignment = xlCenter
   Selection.Font.Size = iFontSize

End Sub

Данная процедура Sub выполняет действия, но не возвращает результат.

В этом примере также использован необязательный (Optional) аргумент iFontSize. Если аргумент iFontSize не передан процедуре Sub, то его значение по умолчанию принимается равным 10. Однако же, если аргумент iFontSize передается процедуре Sub, то в выделенном диапазоне ячеек будет установлен размер шрифта, заданный пользователем.

VBA процедура «Sub»: Пример 2. Выравнивание по центру и применение полужирного начертания к шрифту в выделенном диапазоне ячеек

Следующая процедура похожа на только что рассмотренную, но на этот раз, вместо изменения размера, применяется полужирное начертание шрифта в выделенном диапазоне ячеек. Это пример процедуры Sub, которой не передаются никакие аргументы:

Sub Format_Centered_And_Bold()

   Selection.HorizontalAlignment = xlCenter
   Selection.VerticalAlignment = xlCenter
   Selection.Font.Bold = True

End Sub

Вызов процедуры «Sub» в Excel VBA

Вызов VBA процедуры «Sub» из другой процедуры

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

Sub main()

   Call Format_Centered_And_Sized(20)

End Sub

Если процедура Format_Centered_And_Sized имеет более одного аргумента, то они должны быть разделены запятыми. Вот так:

Sub main()

   Call Format_Centered_And_Sized(arg1, arg2, ...)

End Sub

Вызов VBA процедуры «Sub» из рабочего листа

Процедура Sub не может быть введена непосредственно в ячейку листа Excel, как это может быть сделано с процедурой Function, потому что процедура Sub не возвращает значение. Однако, процедуры Sub, не имеющие аргументов и объявленные как Public (как будет показано далее), будут доступны для пользователей рабочего листа. Таким образом, если рассмотренные выше простые процедуры Sub вставлены в модуль в редакторе Visual Basic, то процедура Format_Centered_And_Bold будет доступна для использования на рабочем листе книги Excel, а процедура Format_Centered_And_Sized – не будет доступна, так как она имеет аргументы.

Вот простой способ запустить (или выполнить) процедуру Sub, доступную из рабочего листа:

  • Нажмите Alt+F8 (нажмите клавишу Alt и, удерживая её нажатой, нажмите клавишу F8).
  • В появившемся списке макросов выберите тот, который хотите запустить.
  • Нажмите Выполнить (Run)

Чтобы выполнять процедуру Sub быстро и легко, можно назначить для неё комбинацию клавиш. Для этого:

  • Нажмите Alt+F8.
  • В появившемся списке макросов выберите тот, которому хотите назначить сочетание клавиш.
  • Нажмите Параметры (Options) и в появившемся диалоговом окне введите сочетание клавиш.
  • Нажмите ОК и закройте диалоговое окно Макрос (Macro).

Внимание: Назначая сочетание клавиш для макроса, убедитесь, что оно не используется, как стандартное в Excel (например, Ctrl+C). Если выбрать уже существующее сочетание клавиш, то оно будет переназначено макросу, и в результате пользователь может запустить выполнение макроса случайно.

Область действия процедуры VBA

В части 2 данного самоучителя обсуждалась тема области действия переменных и констант и роль ключевых слов Public и Private. Эти ключевые слова так же можно использовать применительно к VBA процедурам:

Public Sub AddToCells(i As Integer)

...

End Sub
Если перед объявлением процедуры стоит ключевое слово Public, то данная процедура будет доступна для всех модулей в данном проекте VBA.
Private Sub AddToCells(i As Integer)

...

End Sub
Если перед объявлением процедуры стоит ключевое слово Private, то данная процедура будет доступна только для текущего модуля. Её нельзя будет вызвать, находясь в любом другом модуле или из рабочей книги Excel.

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

Ранний выход из VBA процедур «Function» и «Sub»

Если нужно завершить выполнение VBA процедуры Function или Sub, не дожидаясь её естественного финала, то для этого существуют операторы Exit Function и Exit Sub. Применение этих операторов показано ниже на примере простой процедуры Function, в которой ожидается получение положительного аргумента для выполнения дальнейших операций. Если процедуре передано не положительное значение, то дальнейшие операции не могут быть выполнены, поэтому пользователю должно быть показано сообщение об ошибке и процедура должна быть тут же завершена:

Function VAT_Amount(sVAT_Rate As Single) As Single

   VAT_Amount = 0
   If sVAT_Rate <= 0 Then
      MsgBox "Expected a Positive value of sVAT_Rate but Received " & sVAT_Rate
      Exit Function
   End If

...

End Function

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

Оцените качество статьи. Нам важно ваше мнение:

VBA Call Sub

Introduction to Excel VBA Call Sub

In VBA, we have a function as CALL, which is used for calling the values stored in another Subcategory or Sub procedure. Suppose we have written a code somewhere in a workbook, now while writing another code we need the same code written earlier. So instead of writing the same code again, we can call that complete code or Sub procedure into the current Subcategory or Sub procedure. By this can avoid doing the same activity of workbook again and again.

How to Call Sub in Excel VBA?

Below are the different examples to call Sub in Excel VBA:

You can download this VBA Call Sub Excel Template here – VBA Call Sub Excel Template

Excel VBA Call Sub – Example #1

First, let’s see a single example where we will CALL already written code subcategory or procedure. For this, we need a module.

Go to VBA window and under Insert menu option click on Module as shown below.

VBA Call Sub Example 1-1

After that, we will get a blank page or window of Module. Now in that write a subcategory of code which we are performing or in any other name as shown below.

Code:

Sub Calling()

End Sub

VBA Sub Call Example 1-2

Now use a command of the message box and type any text or word you want to see in the message box. Here we are using “First” as shown below.

Code:

Sub Calling()

MsgBox ("First")

End Sub

VBA Sub Call Example 1-3

Now compile the code and run it by clicking on the Play button which is below the menu bar. We will see a message box containing the message “First” as shown below.

VBA Sub Call Example 1-4

Now after the End in the same module, write another Subcategory or procedure in any name as shown below.

Code:

Sub Arriving()

End Sub

VBA Sub Call Example 1-5

In that again use the command MsgBox and give it message or text as per your choice. Here we have given it “Second” as shown below.

Code:

Sub Arriving()

MsgBox ("Second")

End Sub

VBA Sub Call Example 1-6

Now if we run the complete code then we will get the output of only last Subcategory which is a message box containing message “Second” as shown below.

Result of Example 1-7

Here comes the function CALL, which we will use to call both messages one by one. This will be used in the first subcategory.

For this type Call in the first subcategory before End, followed by the name of that subcategory whose code we want to call. Hereafter MsgBox we are using Call followed by Arriving which is the subcategory name of the code written below.

Code:

Sub Calling()

MsgBox ("First")

Call Arriving

End Sub

Sub Arriving()

MsgBox ("Second")

End Sub

VBA Sub Call Example 1-8

Now compile the complete code from start to end and run it. We will see the message box named with the message “First”. Now click on Ok to proceed further. Once we do that, we will get the second message box containing the message “Second” as shown below. And if click on Ok again, then it will exit from the procedure.

Result of Example 1-9

What if we change the position of Call function from before End to after the first Subcategory as shown below? Now let run the complete code again.

Code:

Sub Calling()

Call Arriving

MsgBox ("First")

End Sub

Sub Arriving()

MsgBox ("Second")

End Sub

VBA Sub Call Example 1-11

It will pop up the message stored in the second subprocedure first which is “Second” followed by the message “First” when we click on Ok as shown below.

Result of Example 1-10

So it’s all up to us, which Sub procedure or category we want to call first.

Excel VBA Call Sub – Example #2

Let’s see another example where we will use a Call function to call different subcategory. For this, we need a new module. Open a Module from the Insert menu. And it gives a Subcategory in any name as shown below.

Code:

Sub VBACall()

End Sub

Example 2-1

Define 3 variables Num1, Num2, and Ans1 in DIM and assign then with Long. We can use Integer or Double as well, depending on one’s use. Long will allow us to consider any length of number.

Code:

Sub VBACall()

Dim Num1 As Long
Dim Num2 As Long
Dim Ans1 As Long

End Sub

Example 2-2

Now give Num1 and Num2 any number of your choice. We have given them 100 and 50 respectively. Considering 100 and 50 will help us to identify the output quickly.

Code:

Sub VBACall()

Dim Num1 As Long
Dim Num2 As Long
Dim Ans1 As Long

Num1 = 100
Num2 = 50

End Sub

Example 2-3

Now use multiplication formula to multiply the numbers stores in Num1 and Num2 and store their answer in Ans1 variable as shown below.

Code:

Sub VBACall()

Dim Num1 As Long
Dim Num2 As Long
Dim Ans1 As Long

Num1 = 100
Num2 = 50

Ans1 = Num1 * Num2

End Sub

VBA Sub Call Example 2-4

In the next line of code, we will use the VBA Object. For this select the sheet with command Worksheet and give it a range of any cell. We have selected the range cell as B1. And at last print the result with any name such as Result or Answer as shown below.

Code:

Sub VBACall()

Dim Num1 As Long
Dim Num2 As Long
Dim Ans1 As Long

Num1 = 100
Num2 = 50

Ans1 = Num1 * Num2

Worksheets(1).Range("B1").Value = "Answer"

End Sub

VBA Sub Call Example 2-5

Now give it the location where we want to see the answer in the same manner as shown above. Here we are choosing cell C1 as output cell and put the last variable Ans1 here.

Code:

Sub VBACall()

Dim Num1 As Long
Dim Num2 As Long
Dim Ans1 As Long

Num1 = 100
Num2 = 50

Ans1 = Num1 * Num2

Worksheets(1).Range("B1").Value = "Answer"
Worksheets(1).Range("C1").Value = Ans1

End Sub

VBA Sub Call Example 2-6

Now run the code. We will see a multiplication result at cell C1.

Result of Example 2-7

Writing another Subcategory below the same code after End.

Code:

Sub VBACall2()

End Sub

VBA Sub Call Example 2-8

Again define 3 variables Num3, Num4, and Ans2 in DIM and assign then with Long.

Code:

Sub VBACall2()

Dim Num3 As Long
Dim Num4 As Long
Dim Ans2 As Long

End Sub

VBA Sub Call Example 2-9

Give Num3 and Num4 the same values like 100 and 50 and add both the numbers.

Code:

Sub VBACall2()

Dim Num3 As Long
Dim Num4 As Long
Dim Ans2 As Long

Num3 = 100
Num4 = 50

Ans2 = Num3 + Num4

End Sub

VBA Sub Call Example 2-10

Now use VBA Object in a similar way as used above and give then range cell as B2 for Answer and C2 for output of Ans2.

Code:

Sub VBACall2()

Dim Num3 As Long
Dim Num4 As Long
Dim Ans2 As Long

Num3 = 100
Num4 = 50

Ans2 = Num3 + Num4

Worksheets(1).Range("B2").Value = "Answer"
Worksheets(1).Range("C2").Value = Ans2

End Sub

VBA Sub Call Example 2-11

To call both results one by one, use Call function it gives it the name of 2nd Subcategory as shown below.

Code:

Sub VBACall()
Dim Num1 As Long
Dim Num2 As Long
Dim Ans1 As Long
Num1 = 100
Num2 = 50
Ans1 = Num1 * Num2
Worksheets(1).Range("B1").Value = "Answer"
Worksheets(1).Range("C1").Value = Ans1

Call VBACall2

End Sub

Sub VBACall2()
Dim Num3 As Long
Dim Num4 As Long
Dim Ans2 As Long
Num3 = 100
Num4 = 50
Ans2 = Num3 + Num4
Worksheets(1).Range("B2").Value = "Answer"
Worksheets(1).Range("C2").Value = Ans2
End Sub

VBA Sub Call Example 2-12

Now compile the entire code and run. We will the first at cell C2, we got the result of the multiplication and at cell C3, a result of the addition.

Result of Example 2-13

To know the proper sequence, we can use MsgBox command as used in Example-1 and see which values called at what sequence.

Pros of Excel VBA Call Sub

  • VBA Call Sub saves time in writing the same code again and again.
  • Calling the VBA sub procedure store in same excel reduces the size of the excel file as well.

Things to Remember

  • Use the message box for test purpose to see the sequential run of multiple codes.
  • Compile the bigger code lines by pressing the F8 key so that the error part can be identified.
  • Save the file in Macro Enable Excel format to retain the written code.
  • Using CALL before End will run the first code first and after the first Subprocedure will run the second code first.

Recommended Articles

This is a guide to VBA Call Sub. Here we discuss how to Call Sub in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Do Until Loop
  2. VBA Get Cell Value
  3. VBA While Loop
  4. VBA RGB

“Computers are useless. They can only give you answers.” – Pablo Picasso.

 
This post provides a complete guide to using the VBA Sub. I also cover VBA functions which are very similar to Subs.

If you want some quick information about creating a VBA Sub, Function, passing parameters, return values etc. then check out the quick guide below.

If you want to understand all about the VBA Sub, you can read through the post from start to finish or you can check out the table of contents below.

Quick Guide to the VBA Sub

Sub Example
Sub

  • Cannot return a value.
Function

  • Can return a value or object.
  • Can run as Worksheet function.
Create a sub Sub CreateReport()

End Sub

Create a function Function GetTotal() As Long

End Function

Create a sub with parameters Sub CreateReport(ByVal Price As Double)

Sub CreateReport(ByVal Name As String)

Create a function with parameters Function GetTotal(Price As Double)

Function GetTotal(Name As String)

Call a sub Call CreateReport
‘ Or
CreateReport
Call a function Call CalcPrice
‘ Or
CalcPrice
Call a sub with parameters Call CreateReport(12.99)

CreateReport 12.99

Call a function with parameters Call CalcPrice(12.99)

CalcPrice 12.99

Call a function and retrieve value
(cannot use Call keyword for this)
Price = CalcPrice
Call a function and retrieve object Set coll = GetCollection
Call a function with params and retrieve value/object Price = CalcPrice(12)
Set coll = GetCollection(«Apples»)
Return a value from Function Function GetTotal() As Long
    GetTotal = 67
End Function
Return an object from a function Function GetCollection() As Collection
    Dim coll As New Collection
    Set GetCollection = coll
End Function
Exit a sub If IsError(Range(«A1»)) Then
     Exit Sub
End If
Exit a function If IsError(Range(«A1»)) Then
     Exit Function
End If
Private Sub/Private Function
(available to current module)
Private Sub CreateReport()
Public Sub/Public Function
(available to entire project)
Public Sub CreateReport()

Introduction

The VBA Sub is an essential component of the VBA language. You can also create functions which are very similar to subs. They are both procedures where you write your code. However, there are differences and these are important to understand. In this post I am going to look at subs and functions in detail and answer the vital questions including:

  • What is the difference between them?
  • When do I use a sub and when do I use a function?
  • How do you run them?
  • Can I return values?
  • How do I pass parameters to them?
  • What are optional parameters?
  • and much more

 
Let’s start by looking at what is the VBA sub?

What is a Sub?

In Excel VBA a sub and a macro are essentially the same thing. This often leads to confusion so it is a good idea to remember it. For the rest of this post I will refer to them as subs.

A sub/macro is where you place your lines of VBA code. When you run a sub, all the lines of code it contains are executed. That means that VBA carries out their instructions.

 
The following is an example of an empty sub

Sub WriteValues()

End Sub

 
You declare the sub by using the Sub keyword and the name you wish to give the sub. When you give it a name keep the following in mind:

  • The name must begin with a letter and cannot contain spaces.
  • The name must be unique in the current workbook.
  • The name cannot be a reserved word in VBA.

 
The end of the Sub is marked by the line End Sub.

 
When you create your Sub you can add some code like the following example shows:

Sub WriteValues()
    Range("A1") = 6
End Sub

What is a Function?

A Function is very similar to a sub. The major difference is that a function can return a value – a sub cannot. There are other differences which we will look at but this is the main one.

You normally create a function when you want to return a value.

 
Creating a function is similar to creating a sub

Function PerformCalc()

End Function

 
It is optional to add a return type to a function. If you don’t add the type then it is a Variant type by default. This means that VBA will decide the type at runtime.

 
The next example shows you how to specify the return type

Function PerformCalc() As Long

End Function

 
You can see it is simple how you declare a variable. You can return any type you can declare as a variable including objects and collections.

A Quick Comparison

Sub:

  1. Cannot return a value.
  2. Can be called from VBAButtonEvent etc.

Function

  1. Can return a value but doesn’t have to.
  2. Can be called it from VBAButtonEvent etc. but it won’t appear in the list of Macros. You must type it in.
  3. If the function is public, will appear in the worksheet function list for the current workbook.

 
Note 1: You can use “Option Private Module” to hide subs in the current module. This means that subs won’t be visible to other projects and applications. They also won’t appear in a list of subs when you bring up the Macro window on the developer tab.

Note 2:We can use the word procedure to refer to a function or sub

Calling a Sub or Function

When people are new to VBA they tend to put all the code in one sub. This is not a good way to write your code.

It is better to break your code into multiple procedures. We can run one procedure from another.

Here is an example:

' https://excelmacromastery.com/
Sub Main()
    
    ' call each sub to perform a task
    CopyData
    
    AddFormulas
    
    FormatData

End Sub

Sub CopyData()
    ' Add code here
End Sub

Sub AddFormulas()
    ' Add code here
End Sub

Sub FormatData()
    ' Add code here
End Sub

 
You can see that in the Main sub, we have added the name of three subs. When VBA reaches a line containing a procedure name, it will run the code in this procedure.

We refer to this as calling a procedure e.g. We are calling the CopyData sub from the Main sub.

There is actually a Call keyword in VBA. We can use it like this:

' https://excelmacromastery.com/
Sub Main()
    
    ' call each sub to perform a task
    Call CopyData
    
    Call AddFormulas
    
    Call FormatData

End Sub

 
Using the Call keyword is optional. There is no real need to use it unless you are new to VBA and you feel it makes your code more readable.

If you are passing arguments using Call then you must use parentheses around them.

For example:

' https://excelmacromastery.com/
Sub Main()
    
    ' If call is not used then no parentheses
    AddValues 2, 4
    
    ' call requires parentheses for arguments
    Call AddValues(2, 4)
End Sub

Sub AddValues(x As Long, y As Long)

End Sub

How to Return Values From a Function

To return a value from a function you assign the value to the name of the Function. The following example demonstrates this:

' https://excelmacromastery.com/
Function GetAmount() As Long
    ' Returns 55
    GetAmount = 55
End Function

Function GetName() As String
    ' Returns John
    GetName = "John"
End Function

 
When you return a value from a function you will obviously need to receive it in the function/sub that called it. You do this by assigning the function call to a variable. The following example shows this:

' https://excelmacromastery.com/
Sub WriteValues()
    Dim Amount As Long
    ' Get value from GetAmount function
    Amount = GetAmount
End Sub

Function GetAmount() As Long
    GetAmount = 55
End Function

 
You can easily test your return value using by using the Debug.Print function. This will write values to the Immediate Window (View->Immediate window from the menu or press Ctrl + G).

' https://excelmacromastery.com/
Sub WriteValues()
    ' Print return value to Immediate Window
    Debug.Print GetAmount
End Sub

Function GetAmount() As Long
    GetAmount = 55
End Function

Using Parameters and Arguments

We use parameters so that we can pass values from one sub/function to another.

The terms parameters and arguments are often confused:

  • A parameter is the variable in the sub/function declaration.
  • An argument is the value that you pass to the parameter.
' https://excelmacromastery.com/
Sub UsingArgs()

    ' The argument is 56
    CalcValue 56
    
    ' The argument is 34
    CalcValue 34

End Sub

' The parameter is amount
Sub CalcValue(ByVal amount As Long)

End Sub

Here are some important points about parameters:

  • We can have multiple parameters.
  • A parameter is passed using either ByRef or ByVal. The default is ByRef.
  • We can make a parameter optional for the user.
  • We cannot use the New keyword in a parameter declaration.
  • If no variable type is used then the parameter will be a variant by default.

The Format of Parameters

Subs and function use parameters in the same way.

The format of the parameter statement is as follows:

' All variables except arrays
[ByRef/ByVal]  As [Variable Type]

' Optional parameter - can only be a basic type
[Optional] [ByRef/ByVal] [Variable name] As <[Variable Type] = 

' Arrays
[ByRef][array name]() As [Variable Type]

Here are some examples of the declaring different types of parameters:

' https://excelmacromastery.com/
' Basic types

Sub UseParams1(count As Long)
End Sub

Sub UseParams2(name As String)
End Sub

Sub UseParams3(amount As Currency)
End Sub

' Collection
Sub UseParamsColl(coll As Collection)
End Sub

' Class module object
Sub UseParamsClass(o As Class1)
End Sub

' Variant
' If no type is give then it is automatically a variant
Sub UseParamsVariant(value)
End Sub

Sub UseParamsVariant2(value As Variant)
End Sub

Sub UseParamsArray(arr() As String)
End Sub

You can see that declaring parameters looks similar to using the Dim statement to declare variables.

Multiple Parameters

We can use multiple parameters in our sub/functions. This can make the line very long

Sub LongLine(ByVal count As Long, Optional amount As Currency = 56.77, Optional name As String = "John")

We can split up a line of code using the underscore (_) character. This makes our code more readable

Sub LongLine(ByVal count As Long _
            , Optional amount As Currency = 56.77 _
            , Optional name As String = "John")

Parameters With a Return Value

This error causes a lot of frustration with new users of VBA.

If you are returning a value from a function then it must have parentheses around the arguments.

The code below will give the “Expected: end of statement” syntax error.

' https://excelmacromastery.com/
Sub UseFunction()
    
    Dim result As Long
    
    result = GetValue 24.99
    
End Sub


Function GetValue(amount As Currency) As Long
    GetValue = amount * 100
End Function
 

 
vba expected end of statement error

 
 
We have to write it like this

result = GetValue (24.99)

ByRef and ByVal

Every parameter is either ByRef or ByVal. If no type is specified then it is ByRef by default

' https://excelmacromastery.com/
' Pass by value
Sub WriteValue1(ByVal x As Long)

End Sub

' Pass by reference
Sub WriteValue2(ByRef x As Long)

End Sub

' No type used so it is ByRef
Sub WriteValue3(x As Long)

End Sub

 
If you don’t specify the type then ByRef is the type as you can see in the third sub of the example.

The different between these types is:

ByVal – Creates a copy of the variable you pass.
This means if you change the value of the parameter it will not be changed when you return to the calling sub/function

ByRef – Creates a reference of the variable you pass.
This means if you change the value of the parameter variable it will be changed when you return to the calling sub/function.

 
The following code example shows this:

' https://excelmacromastery.com/
Sub Test()

    Dim x As Long

    ' Pass by value - x will not change
    x = 1
    Debug.Print "x before ByVal is"; x
    SubByVal x
    Debug.Print "x after ByVal is"; x

    ' Pass by reference - x will change
    x = 1
    Debug.Print "x before ByRef is"; x
    SubByRef x
    Debug.Print "x after ByRef is"; x

End Sub

Sub SubByVal(ByVal x As Long)
    ' x WILL NOT change outside as passed ByVal
    x = 99
End Sub

Sub SubByRef(ByRef x As Long)
    ' x WILL change outside as passed ByRef
    x = 99
End Sub

 
The result of this is:
x before ByVal is 1
x after ByVal is 1
x before ByRef is 1
x after ByRef is 99

 
You should avoid passing basic variable types using ByRef. There are two main reasons for this:

  1. The person passing a value may not expect it to change and this can lead to bugs that are difficult to detect.
  2. Using parentheses when calling prevents ByRef working – see next sub section

A Little-Known Pitfall of ByRef

There is one thing you must be careful of when using ByRef with parameters. If you use parentheses then the sub/function cannot change the variable you pass even if it is passed as ByRef. 

In the following example, we call the sub first without parentheses and then with parentheses. This causes the code to behave differently.

 
For example

' https://excelmacromastery.com/
Sub Test()

    Dim x As Long

    ' Call using without Parentheses - x will change
    x = 1
    Debug.Print "x before (no parentheses): "; x
    SubByRef x
    Debug.Print "x after (no parentheses): "; x

    ' Call using with Parentheses - x will not change
    x = 1
    Debug.Print "x before (with parentheses): "; x
    SubByRef (x)
    Debug.Print "x after (with parentheses): "; x

End Sub

Sub SubByRef(ByRef x As Long)
    x = 99
End Sub

 
If you change the sub in the above example to a function, you will see the same behaviour occurs.

However, if you return a value from the function then ByRef will work as normal as the code below shows:

' https://excelmacromastery.com/
Sub TestFunc()

    Dim x As Long, ret As Long

    ' Call using with Parentheses - x will not change
    x = 1
    Debug.Print "x before (with parentheses): "; x
    FuncByRef (x)
    Debug.Print "x after (with parentheses): "; x
    
    ' Call using with Parentheses and return - x will change
    x = 1
    Debug.Print "x before (with parentheses): "; x
    ret = FuncByRef(x)
    Debug.Print "x after (with parentheses): "; x


End Sub

Function FuncByRef(ByRef x As Long)
    x = 99
End Function

As I said in the last section you should avoid passing a variable using ByRef and instead use ByVal.

This means

  1. The variable you pass will not be accidentally changed.
  2. Using parentheses will not affect the behaviour.

ByRef and ByVal with Objects

When we use ByRef or ByVal with an object, it only affects the variable. It does not affect the actual object.

If we look at the example below:

' https://excelmacromastery.com/
Sub UseObject()
    
    Dim coll As New Collection
    coll.Add "Apple"
    
    ' After this coll with still reference the original
    CollByVal coll
    
    
    ' After this coll with reference the new collection
    CollByRef coll
    
End Sub

Sub CollByVal(ByVal coll As Collection)
    
    ' Original coll will still reference the original
    Set coll = New Collection
    coll.Add "ByVal"

End Sub

Sub CollByRef(ByRef coll As Collection)
    
    ' Original coll will reference the new collection
    Set coll = New Collection
    coll.Add "ByRef"

End Sub

When we pass the coll variable using ByVal, a copy of the variable is created. We can assign anything to this variable and it will not affect the original one.

When we pass the coll variable using ByRef, we are using the original variable. If we assign something else to this variable then the original variable will also be assigned to something else.

You can see find out more about this here.

Optional Parameters

Sometimes we have a parameter that will often be the same value each time the code runs. We can make this parameter Optional which means that we give it a default value.

It is then optional for the caller to provide an argument. If they don’t provide a value then the default value is used.

In the example below, we have the report name as the optional parameter:

Sub CreateReport(Optional reportName As String = "Daily Report")

End Sub

 
If an argument is not provided then name will contain the “Daily Report” text

' https://excelmacromastery.com/
Sub Main()
    
    ' Name will be "Daily Report"
    CreateReport
    
    ' Name will be "Weekly Report"
    CreateReport "Weekly Report"

End Sub

The Optional parameter cannot come before a normal parameter. If you do this you will get an Expected: Optional error.

VBA Expected Optional

 
 
When a sub/function has optional parameters they will be displayed in square parentheses by the Intellisense.

In the screenshot below you can see that the name parameter is in square parentheses.

 

A sub/function can have multiple optional parameters. You may want to provide arguments to only some of the parameters.

There are two ways to do this:
If you don’t want to provide an argument then leave it blank.

A better way is to use the parameter name and the “:=” operator to specify the parameter and its’ value.

The examples below show both methods:

' https://excelmacromastery.com/
Sub Multi(marks As Long _
            , Optional count As Long = 1 _
            , Optional amount As Currency = 99.99 _
            , Optional version As String = "A")
            
    Debug.Print marks, count, amount, version
    
End Sub


Sub UseBlanks()

    ' marks and count
    Multi 6, 5
    
    ' marks and amount
    Multi 6, , 89.99
    
    ' marks and version
    Multi 6, , , "B"
    
    ' marks,count and version
    Multi 6, , , "F"

End Sub

Sub UseName()

    ' marks and count
    Multi 12, count:=5
    
    ' marks and amount
    Multi 12, amount:=89.99
    
    ' marks and version
    Multi 12, version:="B"
    
    ' marks,count and version
    Multi 12, count:=6, version:="F"

End Sub

 
Using the name of the parameter is the best way. It makes the code more readable and it means you won’t have error by mistakenly adding extra commas.

wk.SaveAs "C:Docsdata.xlsx", , , , , , xlShared
    
wk.SaveAs "C:Docsdata.xlsx", AccessMode:=xlShared

IsMissing Function

We can use the IsMissing function to check if an Optional Parameter was supplied.

Normally we check against the default value but in certain cases we may not have a default.

We use IsMissing with Variant parameters because it will not work with basic types like Long and Double.

' https://excelmacromastery.com/
Sub test()
    ' Prints "Parameter not missing"
    CalcValues 6
    
    ' Prints "Parameter missing"   
    CalcValues
    
End Sub

Sub CalcValues(Optional x)

    ' Check for the parameter
    If IsMissing(x) Then
        Debug.Print "Parameter missing"
    Else
        Debug.Print "Parameter Not missing"
    End If

End Sub

Custom Function vs Worksheet Function

When you create a function it appears in the function list for that workbook.

 
Have a look at the function in the next example.

Public Function MyNewFunction()
    MyNewFunction = 99
End Function

 
If you add this to a workbook then the function will appear in the function list. Type “=My” into the function box and the function will appear as shown in the following screenshot.

 
Worksheet Function
If you use this function in a cell you will get the result 99 in the cell as that is what the function returns.

Conclusion

The main points of this post are:

  • Subs and macros are essentially the same thing in VBA.
  • Functions return values but subs do not.
  • Functions appear in the workbook function list for the current workbook.
  • ByRef allows the function or sub to change the original argument.
  • If you call a function sub with parentheses then ByRef will not work.
  • Don’t use parentheses on sub arguments or function arguments when not returning a value.
  • Use parentheses on function arguments when returning a value.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

What is Call Sub in VBA?

We can execute all the sub-procedures of the same module in a single subroutine, and the process of executing them in a single VBA subroutineSUB in VBA is a procedure which contains all the code which automatically gives the statement of end sub and the middle portion is used for coding. Sub statement can be both public and private and the name of the subprocedure is mandatory in VBA.read more is called “Call Sub.”

Sometimes, we may need to write a huge amount of code, and writing them in a single macro creates many problems while debugging the code. Unfortunately, at the start, everybody tends to do this purely because of the lack of knowledge of the “Call Sub” method.

Keeping all the codes in a single sub procedure is not a good practice. Instead, we need to break them into multiple sub procedures to simplify the code.

Table of contents
  • What is Call Sub in VBA?
    • How to Call Subroutine in Excel VBA?
    • Recommended Articles

VBA Call Sub

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Call Sub (wallstreetmojo.com)

How to Call Subroutine in Excel VBA?

Running the excel macroA macro in excel is a series of instructions in the form of code that helps automate manual tasks, thereby saving time. Excel executes those instructions in a step-by-step manner on the given data. For example, it can be used to automate repetitive tasks such as summation, cell formatting, information copying, etc. thereby rapidly replacing repetitious operations with a few clicks.
read more
from one procedure to another makes life easier purely based on saving a lot of time while running and debugging the code in case of any error.

You can download this VBA Call Sub Excel Template here – VBA Call Sub Excel Template

Code:

Sub Code_1()

  Range("A1").Value = "Hello"

End Sub

Sub Code_2()

  Range("A1").Interior.Color = rgbAquamarine

End Sub

VBA Call Sub Example 1

In the above image, we have two subprocedures. The first one is “Code_1,” and the second one is “Code_2”.

In the first VBA call subcode, we just wrote a code to insert a value to cell A1 as “Hello.” In the second sub procedure, we have written the code to change the interior color of cell A1 to “rgbAquamarine.”

We will run the first code, “Code_1”.

VBA Call Sub Example 1-1

We will run the second code, “Code_2”.

VBA Call Sub Example 1-2

Here, we have executed the code times.

By using the VBA “call Sub,” we can execute both the sub procedures in a single macro. First, we need to add the word “Call,” followed by a macro name.

Look at the below graphic picture.

VBA Call Sub Example 1-3

We have only mentioned the code as “Call Code_2” in the first subprocedure. Now to understand, let us run the code line by line. Press the F8 key. It will highlight the macro name.

VBA Call Sub Example 1-4

Press the F8 key one more time. It will jump to the next line.

VBA Call Sub Example 1-5

The yellow-colored line shows the highlighted code is about to execute if we press the F8 key again. Press the F8 key now.

Example 1-6

As we can see, it has inserted the word “Hello” into cell A1. So now, the “Call Code_2” line highlights.

“Call Code_2” has the task of changing the interior color of cell A1 and the word “Call Code_2” will execute this code from the actual sub procedure only.

But press the F8 key to see the magic.

Example 1-7

It has jumped to the mentioned sub procedure name. Press the F8 key once again.

Example 1-8

Now, the actual task line highlights. To execute this, press the F8 key one more time.

Example 1-9

Like this, we can execute many sub-procedures from one sub procedure by calling the sub procedure by its name “Call.”

Note:

  • We can execute the macro of another sub procedure without using the word “Call” but just by mentioning the macro name itself.
  • It is not the best practice because if the macro sub procedure contains parenthesis that you want to execute, then the “Call” word is mandatory.
  • We always think of using the word “Call” because it is just a four-letter word, allowing others to understand the code correctly.

Recommended Articles

This article has been a guide to Excel VBA Call Sub. Here, we learn how to call a subroutine in Excel VBA, practical examples, and a downloadable Excel template. In addition, below are some useful Excel articles related to VBA: –

  • Excel VBA Tutorial for BeginnersVisual Basic for Applications (VBA) tutorial provides extensive learning of this Microsoft programming language for its application on Microsoft products like Excel, Word, and PowerPoint. It facilitates the user to do the programming in the Visual Basic Editor (VBE), a platform to write codes for executing various tasks in excel.read more
  • VBA EndEnd is a VBA statement that can be used in a variety of ways in VBA applications. Anywhere in the code, a simple End statement can be used to instantly end the execution of the code. In procedures, the end statement is used to end a subprocedure or any loop function, such as ‘End if’.read more
  • Today in VBAVBA Today refers to the current date. In the worksheet, the function does the same thing and provides the current date and time. The method to get the current date is by using the date function, and unlike the now function, the date function only gives us the current date.read more
  • Subscript Out of Range in VBASubscript out of range is an error in VBA that occurs when we attempt to reference something or a variable that does not exist in the code. For example, if we do not have a variable named x but use the msgbox function on x, we will receive a subscript out of range error.read more

Понравилась статья? Поделить с друзьями:
  • Vba excel выделить ячейку по координатам
  • Vba excel выделить ячейку по адресу
  • Vba excel выделить ячейки только с данными
  • Vba excel выделить текст жирным
  • Vba excel выделить текст в textbox