Open In App

VBA Subroutine in Excel – How to Call Sub in VBA?

When a specified action is performed on a worksheet with the help of a collection of code known as a VBA Subroutine. It also helps to read an external file, also it can open other applications from Excel. A large piece of code can be broken into small parts so that we can manage it easily. Let’s learn why to use submarines:

Naming Rules of Subroutines

Syntax



Private Sub function_name( ByVal arg1 As String, ByVal arg2 As String)

End Sub



Syntax Explanation

Code

Action

“Private Sub function_name(…)” Private is the keyword which is representing the scope of the subroutine. The name of the subroutine i.e function_name will be mentioned after the Sub keyword which starts the body of the subroutine.
“ByVal arg1 As String, ByVal arg2 As String” Two parameters of data type String are declared whose names are arg1 and arg2.
“End Sub” The body of the subroutine is ended.

How to call Sub in VBA?

Step 1: Select the developer tab and click Insert drop-down list from the control box.

 

Step 2: Choose the command button from ActiveX Controls Box.

 

Step 3: Draw the command button in the excel sheet.

 

Step 4: Press Alt + F11 to open the VBA code.

Step 5: Write the following subroutine with the name “display” which will display a name in the message box once its function gets called.

 

Step 6: To call the subroutine we need to right-click on the command button and then select view code.

 

Step 7: Write the following code to call the display function by clicking the command button.

 

The following code displays the overall code of the program.

 

Article Tags :