Conditionally Call A Subroutine

You can conditionally move out of any location in a subroutine to run another subroutine or function. You can accomplish this by using a conditional VBA statement, such as an If Then statement, and combining it with a procedure call statement. When you combine the Call statement with a conditional statement, the other procedure is only called if the condition is met.

When you use this type of structure, the If Then statement checks the specified condition. If the value of the condition is true, the control passes to the specified subroutine or function. After the subroutine completes processing, control returns to the next line of code in the original subroutine. If you do not want to continue processing the first subroutine after calling the second, you need to use an Exit Sub statement at that point to exit the subroutine without running any other statements.

When VBA encounters an Exit Sub statement, it stops processing of the subroutine, and does not process any VBA statements that follow the statement. Remember to place the Exit Sub statement directly after the Call statement to ensure that VBA immediately exits the subroutine after control returns from the other procedure.

Keep in mind, you can only use the Call statement to call another subroutine or function within the same project. VBA does not provide a method for calling subroutines and functions that exist in other projects. To access functions and subroutines that exist in other projects, you must copy the modules that contain them and insert the copies in your current project. You can copy a module using the Project Explorer window. See Chapter 2 for more information about working with the Project Explorer window.

CONDITIONALLY CALL A SUBROUTINE

CONDITIONALLY CALL A SUBROUTINE

—n Create a new subroutine.

< Type code required to determine when to jump to another macro.

Q Type Exit Sub.

—n Create a new subroutine.

L-B Declare and initialize any variables for the subroutine.

< Type code required to determine when to jump to another macro.

-Q Type If Condition Then, replacing Condition with the condition to check.

L0 Type Call NewProc(), replacing NewProc() with the name of the procedure to call.

Q Type Exit Sub.

Q Type any additional VBA commands required for subroutine.

0 0

Responses

  • alexis
    How to recall a subroutine in a subroutine using vba?
    7 years ago
  • asmara
    How to call subroutine conditional on even cell?
    1 year ago

Post a comment