Excel vba call sub from sub

Return to VBA Code Examples

In this Article

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

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

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

Running a Sub Procedure from another Sub Procedure

Consider the 3 Sub Procedures below:

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

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

vba run subs

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

Using the Call Statement

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

Sub TestRoutine() 
   Call RunRoutine1 
   Call RunRoutine2 
End Sub

vba run subs call

Calling a Sub with Arguments

It is also possible to call a sub with arguments

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

vba run sub parameters

Calling a Sub with Named Arguments

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

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

vba run sub multi parameters

VBA Coding Made Easy

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

Learn More!

Содержание

  1. Calling Sub and Function procedures
  2. Call Sub procedures with more than one argument
  3. Use parentheses when calling function procedures
  4. Pass named arguments
  5. See also
  6. Support and feedback
  7. VBA Call / Run Sub From another Subroutine
  8. Running a Sub Procedure from another Sub Procedure
  9. Using the Call Statement
  10. Calling a Sub with Arguments
  11. Calling a Sub with Named Arguments
  12. VBA Coding Made Easy
  13. VBA Code Examples Add-in
  14. VBA Sub
  15. Excel VBA Sub Procedure
  16. How to write VBA Sub Procedures?
  17. Example #1 – Simple Sub Procedure
  18. Example #2 – Simple Subroutine Task
  19. Types of VBA Subroutine
  20. Recommended Articles
  21. VBA Call Sub
  22. What is Call Sub in VBA?
  23. How to Call Subroutine in Excel VBA?
  24. Recommended Articles

Calling Sub and Function procedures

To call a Sub procedure from another procedure, type the name of the procedure and include values for any required arguments. The Call statement is not required, but if you use it, you must enclose any arguments in parentheses.

Use a Sub procedure to organize other procedures so they are easier to understand and debug. In the following example, the Sub procedure Main calls the Sub procedure MultiBeep , passing the value 56 for its argument.

After MultiBeep runs, control returns to Main , and Main calls the Sub procedure Message . Message displays a message box; when the user clicks OK, control returns to Main , and Main finishes.

Interested in developing solutions that extend the Office experience across multiple platforms? Check out the new Office Add-ins model. Office Add-ins have a small footprint compared to VSTO Add-ins and solutions, and you can build them by using almost any web programming technology, such as HTML5, JavaScript, CSS3, and XML.

Call Sub procedures with more than one argument

The following example shows two ways to call a Sub procedure with more than one argument. The second time it is called, parentheses are required around the arguments because the Call statement is used.

Use parentheses when calling function procedures

To use the return value of a function, assign the function to a variable and enclose the arguments in parentheses, as shown in the following example.

If you are not interested in the return value of a function, you can call a function the same way you call a Sub procedure. Omit the parentheses, list the arguments, and don’t assign the function to a variable, as shown in the following example.

If you include parentheses in the preceding example, the statement causes a syntax error.

Pass named arguments

A statement in a Sub or Function procedure can pass values to called procedures by using named arguments. You can list named arguments in any order. A named argument consists of the name of the argument followed by a colon and an equal sign (:=), and the value assigned to the argument.

The following example calls the MsgBox function by using named arguments with no return value.

The following example calls the MsgBox function by using named arguments. The return value is assigned to the variable.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

VBA Call / Run Sub From another Subroutine

In this Article

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

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

Running a Sub Procedure from another Sub Procedure

Consider the 3 Sub Procedures below:

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

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

Using the Call Statement

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

Calling a Sub with Arguments

It is also possible to call a sub with arguments

Calling a Sub with Named Arguments

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

VBA Coding Made Easy

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

VBA Code Examples Add-in

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

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

Источник

VBA Sub

Excel VBA Sub Procedure

SUB in VBA is also known as a subroutine or a procedure that contains all the code. It is an inbuilt statement in VBA, and when used, it automatically gives us the statement of the end sub. The middle portion one may use for coding, the sub statement can be both public and private, and the subprocedure’s name is mandatory in VBA.

Sub means Sub Procedure in VBA. Sub Procedures are used to perform a specific set of tasks provided in the form of code. It performs only the task mentioned in the code as per the VBA language but does not return any value.

Table of contents

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

How to write VBA Sub Procedures?

It is important to understand the structure of the sub procedure to write sub procedure codes. Below is the structure.

To start the sub procedure, we need to use the word “Sub.” We need to give a name to the Sub as a procedure name. Procedure Name is nothing but our macro name. We do not usually have parameters inside the parenthesis in the VBA sub procedure.

After writing the Sub Procedure name, we need to write the tasks that we need to do. Then comes the End statement, i.e., End Sub.

Example #1 – Simple Sub Procedure

Now, take a look at the simple sub procedure writing methods.

Step 1: Start the word “Sub” in the module.

Step 2: Now name the macro name or procedure name.

Step 3: After giving the name to the sub procedure, just hit the enter key. It will automatically apply the end statement.

Now, we can see two things here, one is the start, and another is the end of the subprocedure. For better understanding, we can call it “Head” and “Tail.”

Between the head and tail of the macro, we need to write our code to perform some tasks.

Example #2 – Simple Subroutine Task

Now, we will see how to perform some simple actions here.

Assume you want to insert the value “Excel VBA” in cell A1.

Step 1: Start the sub procedure by using the above methods.

Code:

Step 2: To access cell A1 we need to use the word RANGE.

Code:

Step 3: It asks what cell1 you want to refer to is? In this case, it is an A1 cell.

Code:

Step 4: We need to insert the value “Excel VBA,” so select the VALUE property by putting a dot after the range.

Code:

When you start typing the word VALUE, you will see many options. These options are called an IntelliSense list, which predicts based on your typing. It is like how formulas will appear in the worksheet when we start typing the formula.

Step 5: After selecting VALUE, put an equal sign and enter the value in doubles quotes as “Excel VBA.”

Code:

So, we have completed it.

Now, we need to execute this task. To execute the task, we had a return. So, we need to run this code by pressing the RUN button in the visual basic editor window.

As soon as you run the code, you will get the “Excel VBA” value in cell A1.

Types of VBA Subroutine

We have two more types in sub procedure: Public Sub Procedure and Private Sub Procedure.

The words “Public” and “Private” are accessibility modifiers that allow us to use them differently.

  • Public Sub Procedure allows us to use the procedure in all the workbook modules.
  • Private Sub Procedure allows us to use the procedure only in the current module.

For example, look at the below image of the Public Code, which is there in Module 1.

Now, in Module 2 also, we can use this sub procedure.

Action1 is the name of the sub procedure we have used in Module 1.

In Module 2, we have mentioned it as “Call Action1”. It means when you run the sub procedure, it will execute the subprocedure Action1 from Module 1.

One cannot access Private Sub Procedures from a different module. We need to access them from the same module only.

Recommended Articles

This article has been a guide to VBA Sub. Here, we learn how to invoke a sub procedure in Excel VBA and types of subroutines, along with examples and downloadable templates. Below are some useful articles related to VBA: –

Источник

VBA Call Sub

What is Call Sub in VBA?

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

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

How to Call Subroutine in Excel VBA?

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”.

We will run the second code, “Code_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.

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.

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

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

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.

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

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

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: –

Источник

Содержание

  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, которая показывает пользователю всплывающее окно с предупреждением.

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

  • #1

I have a sub routine that is run. Within this sub routine, a number of variables are declared and stored with certain values. I then would like to call a second sub routine, let’s call it «SecondSub».

Within the first sub routine, I have the code in place to call the SecondSub (Call SecondSub).

My question is this: what needs to be done for those variables that were stored in the original sub routine to be able to be used in the SecondSub that is called by the original?

Thanks,

How to find 2nd largest value in a column?

MAX finds the largest value. =LARGE(A:A,2) will find the second largest. =SMALL(A:A,3) will find the third smallest

  • #2

Declare them outside the procedures

Code:

Public Var1 as Long
Public Var2 as String
 
Sub RunSub1
 
'...code
'...code
'...code
 
Call SubRun2
End Sub
 
Sub SubRun2
'will now have access to Var1 and Var2 as defined in SubRun1
End Sub

  • #3

I figured it was something simple like that… I knew I had done it before, but just couldn’t remember what I did…. thanks a lot!

  • #4

if you are declaring the variables in the first sub then use this:

Code:

Sub subOne()
    Dim var1 As Long
    Dim var2 As Long
    
    'code
    
    subTwo var1, var2
End Sub

Sub subTwo(ByVal v1 As Long, ByRef v2 As Long)
    'code
End Sub

note the «ByVal» and «ByRef» in this line «Sub subTwo(ByVal v1 As Long, ByRef v2 As Long)»

ByVal means that only the value is passed to subTwo and subTwo cannot change the value

ByRef means that a reference is passed to subTwo so subTwo can change the value of the variable and subOne will have access to the changed value

Понравилась статья? Поделить с друзьями:
  • Excel vba byval target as range
  • Excel vba byref argument type mismatch vba
  • Excel vba buttons add
  • Excel vba button onaction
  • Excel vba chr коды