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
- Sub subroutine()
- MsgBox " I am called by another subroutine"
- End Sub
- Sub call_subroutine()
- subroutine
- End Sub
A glimpse of above code in the editor is as shown below
The Output is as shown below