VBA Subroutine in Excel

A Subroutine is nothing but a piece of code that performs some specific task.

There are two important uses of subroutine in VBA programming which are:

1.Manageable code by breaking code into smaller pieces

When coding a large complex program, imagine what if you code the entire logic in a single subroutine?

In this case, it will be difficult to debug and fix errors or do modifications. So, breaking code into smaller subroutines will enhance the programming experience

2.Code Reusability

What if you want to use a functionality repeatedly at various places in a your program?

In this case, It will be convinient to place that set of code in a separate subroutine and just calling that subroutine whenever needed, instead of repeating the same set of code at every place, where it is required.This feature is very helpful whlile programming.

It should also be noted that, there is a restriction on the size of a single subroutine in excel and hence subroutine is inevitable in larger programs.

The Subroutine can take arguments but does not return any value.This is most important thing with Subroutine.

The following example illustrates the Sub Routine

  1. Sub subroutine()
  2. MsgBox " I am called by another subroutine"
  3. End Sub
  4. Sub call_subroutine()
  5. subroutine
  6. End Sub

A glimpse of above code in the editor is as shown below

excel vba subroutine

The Output is as shown below

excel vba subroutine

 

You can find similar Excel Questions and Answer hereunder

1) What is a function in VBA. How to create a function and how to call a function

2) What are the various functions of the worksheet in Excel VBA

3) How to format variable with VBA with the very useful format function. Define the number of decimal, the way a date is formated

4) How to modify strings in VBA, what are the functions you can manipulate strings with

5) How can worksheet functions be accessed in VBA?

6) How to convert a number or string into a data with the cdate function

7) What is a module in VBA. How to create a module in VBA

8) How to use logical operators in VBA

9) What is variable scope in VBA, how do variable can be reach from other function or routines in VBA

10) Here we show you advanced VBA array functions, like splitting arrays, Lbound, Ubound

 

Here the previous and next chapter