In this article, I will introduce Sub in VBA. This is considered advanced knowledge of programming languages, but because the content in VBA is very messy and related to each other, so in this article, I will briefly introduce what Sub is and how to create Sub.
Nội dung
1. What is a Sub in VBA?
A subroutine is a set of code that performs a specific task and does not return a result. Subroutines are used to divide large pieces of code into smaller, more manageable pieces. After creating Sub, we can call it to use many times without having to recode.
Example of free tuts .net: If you want to write bold, italic and uppercase code in cell A1, the VBA code will look like this.
If I want to use this code in 100 other places of a huge VBA program, I will have to rewrite it 100 times, which will cause difficulty in future maintenance.
Instead we will put that code into a Sub.
And wherever you want to use this code, just call it like this: Call
BoldItalicUcaseText()
2. Sub syntax in VBA
To create a sub, use the following syntax:
Sub sub_name()
' Statement
End Sub
In there:
sub_name
is the name of the sub you want to set. You cannot use special characters to set the name.statement
are the code that will be run every time the sub is called.
Sub showMessage()
MsgBox "Learn Sub in VBA"
End Sub
3. Calling a Sub Procedure in VBA
Without the Call
keyword: SubName arguments
Sub greet()
MsgBox "Hello, World!"
End Sub
With the Call
keyword: Call SubName(arguments)
greet ' Without Call
Call greet ' With Call (optional)
The choice of using Call
is optional. The output is the same, but the Call
keyword can make your code more readable in some cases.
4. Why do we use sub?
- Splitting code into smaller chunks : An average computer program has thousands of lines of source code. This is very complex. Subroutines help solve this problem by breaking the program into smaller, manageable chunks of code.
- Code Reuse : Suppose you have a program that needs to access a database, most of the program’s windows will need to interact with the database. Instead of writing separate code for these windows, you can create a function that handles all database interactions. You can then call it from any window you want.
- Subroutines and functions are self-documenting code . Let’s say you have a function that calculates loan interest and another function that connects to a database. By just looking at the name of the subroutine or function, the programmer will be able to tell what the program does.
Hopefully, through this article, you can understand more about the knowledge in VBA. You can refer to more at: Calling Sub and Function procedures.
See more:
- What is a module in VBA? Basic operations to work with modules
- Function Procedures in VBA: A Complete Guide