VBA (Visual Basic for Applications) is a programming language integrated into Microsoft Office applications such as Word, Excel, and PowerPoint. With VBA, users can automate manual tasks, increasing efficiency and productivity. The main advantages of using VBA include time savings, increased accuracy, and the flexibility to tailor it to specific needs.
VBA is essential for workplace productivity. Users can manage big data, create automated reports, and structure documents in a consistent format. For example, in a monthly sales report, VBA can automatically collect data, calculate total sales, and generate charts.
VBA’s daily use is very diverse. In Excel, it can be used for automated financial reports and data processing with pivot tables. In Word, users can create automated template documents and manage document elements. In PowerPoint, VBA allows you to organize presentation slides from Excel data more efficiently.


1. Understanding the Procedure in VBA
In Visual Basic for Applications (VBA), there are two main types of procedures for executing code: Subprocedures (or subs) and Functions.
a. Subprocedures
A subprocedure is a piece of code that is created to perform a specific task without returning a value. Subs are often used to execute a series of commands or macros that perform actions, such as changing the format of a document or displaying a message.
b. Functions
Functions is a procedure that also performs a specific task, but returns a value. Functions can be used in expressions and provide results that can be used again in code.
Difference between Subprocedures and Functions
| Aspects | Sub | Function |
| Use | Perform specific tasks | Perform tasks and return values |
| Early Writing | Starting with Sub | Starting with a Function |
| Return of Value | Doesn’t return a value | Returning a value with a Return |
| Usage Examples | Running macros, modifying documents | Calculate the results of calculations or validate data |
Here is a simple example to understand Sub:
Sub HelloWorld()
' Displays the message “Hello, World!” in a dialog box
MsgBox “Hello, World!”
End SubExplanation:
- Sub HelloWorld(): Defines a procedure named “HelloWorld”.
- MsgBox: VBA built-in commands to display a dialog box containing messages.
- End Sub: Marks the end of the Sub procedure.
For Function, here’s a simple example:
Function AddNumbers(ByVal a As Integer, ByVal b As Integer) As Integer
' Returns the sum of two numbers
AddNumbers = a + b
End FunctionThis function can be called in other code or directly in Excel, such as using a regular formula:
=AddNumbers(5, 10)2. Variables and Constants
What are Variables and How to Declare Them
The variable is a place to store data that can change as the program runs. In VBA, a variable must be declared before it can be used with the Dim keyword, followed by the name of the variable and its data type. For example, to declare a variable of type string, you can use the following syntax:
Dim name As String ' Stores text
Dim age As Integer ' Stores integer
Dim height As Double ' Stores decimal numberBy declaring variables, you tell VBA about the type of data to be stored, which helps in memory management and makes the code clearer.
The Importance of Using Option Explicit
Using Option Explicit at the beginning of a VBA module is highly recommended. By adding this statement, you are required to declare all variables before using them. This helps avoid typos and logical errors that often arise due to the use of undeclared or misspelled variables. Examples of use:
Option Explicit
Sub Example()
Dim age As Integer
age = 25
End SubWith Option Explicit, if you try to use a variable without declaring it first, VBA will give an error, thus helping to maintain the quality of the code.
The Concept of Constants and When to Use Them
A constant is a value that is fixed and does not change during the program. By using constants, the code becomes easier to read and manage, as you can name frequently used values. To declare a constant, use the keyword Const. An example of a constant declaration is:
Const PI As Double = 3.14159You should use constants when they have values that won’t change during the program, such as mathematical values (for example, PI), certain constraints, or fixed text. This way, if there is a change in value in the future, you just need to change it in one place.
3. Statements and Operators
In VBA, statements are lines of code that describe an action, define an item, or assign a value to a variable. Statements function like sentences in everyday language.
Normally, each line of code has only one statement, but you can put multiple statements in a single line by separating them with colons. Examples of statements include declaring variables, calling procedures, or setting the value of an object’s property.
A statement can be in the form of:
- Variable declaration: For example, Dim x As Integer.
- Grade assignment: For example, x = 10.
- Procedure or function calls: For example, Call MsgBox(“Hello!”).
- Flow control: For example, If, For, or Do While statements.
Arithmetic Operator
Arithmetic operators are used to perform mathematical calculations.
| Operator | Description | Example | Result |
| + | Addition | 5 + 3 | 8 |
| – | Reduction | 10 – 4 | 6 |
| * | Multiplication | 6 * 7 | 42 |
| / | Division | 20 / 4 | 5 |
| ^ | Rank | 2^3 | 8 |
| Mod | The rest of the division | 10 Mod 3 | 1 |
Logic Operator
Logical operators are used to make decisions based on condition statements.
| Operator | Description | Example | Result |
| And | Worth True if both conditions are worth True | (5 > 3) And (2 < 4) | True |
| Or | Worth True jika salah satu kondisi True | (5 > 3) Or (2 > 4) | True |
| Not | Inverting condition values | Not (5 > 3) | False |
4. Writing and Running Macros
To create a macro in VBA, you need to write a procedure that is constrained by Sub and End Sub statements.
Once you’ve created a macro, you can run it through the Macros Dialog Box. Here are the steps to run the macro:
- Open a Microsoft Office application (such as Excel or Word).
- Click the Developer tab in the Ribbon. If this tab doesn’t appear, you may need to enable it in settings.
- Click the Macros button to open the dialog box.
- In the dialog box, select the name of the macro you want to run from the list.
- Click the Run button to execute the selected macro.
5. Manipulation of Objects and Properties
In VBA, an object is an element that can be changed through code. Two objects that are often used in Microsoft Word are ActiveDocument and Selection.
- ActiveDocument: This is an object that represents the document that is currently open in Word. You can access and change the properties and methods of this document.
- Selection: This is an object that represents the text or element that is being selected in the document. If no one is selected, this object will indicate the cursor position.
You can change various object properties in VBA to format the document. Some of the properties that are frequently changed are:
- Font: Change the text font type.
- Size: Resize the text.
- Bold: Determines whether the text is displayed in bold.
Here’s an example of how to change some of these properties:
Sub FormatTeks()
With Selection.Font
.Name = “Arial” ' Sets the font type
.Size = 12 ' Sets the font size
.Bold = True ' Sets the text to bold
End With
End SubIn the example above, the FormatTeks procedure uses a Selection object to change the font, size, and formatting of the text to bold.
6. Methods and Arguments
Metode in VBA is a command that is used to perform a specific action on an object. For example, the Open method is used to open a new file. Here is an explanation and example of using the Open method:
Documents.Open “C:\Path\To\File.docx”In the example above, the Open method is used to open a file located in C:\Path\To\File.docx.
An argument is a value assigned to a method to execute a particular action. There are two types of arguments: mandatory and optional.
- Required Arguments: Arguments that must be present when using the method. Without this argument, the method cannot be executed.
- Optional Arguments: Arguments that don’t have to be present when using the method. However, this argument can provide additional benefits to the actions taken.
An example of the use of mandatory and optional arguments can be seen in the Close method for closing a document:
' Mandatory argument: Document to close
ActiveDocument.Close
' Optional argument: Symbol to save changes (default=True)
ActiveDocument.Close SaveChanges:=FalseIn the example above, the mandatory argument is ActiveDocument, while the optional argument is SaveChanges.
Tips and Tricks for Beginners
Immediate Window is a very useful tool in Visual Basic Editor (VBE) that allows you to run VBA statements directly and see the results. This is especially useful for debugging, as you can:
- You can type a VBA statement in this window and see the result right away without having to run the entire macro.
- By typing the name of the variable, you can find out the current value of the variable.
- You can directly change the properties of the object to see the impact on the app.
Understanding VBA documentation is crucial for beginners for several reasons. First, the documentation provides comprehensive information about the objects, methods, and properties available in VBA.
Second, many sections in the documentation are accompanied by code examples that make it easy to understand how to take advantage of the various features. Finally, if you encounter an error, the documentation usually explains the error and provides a solution to resolve it.
You can access the documentation by pressing F1 while in the VBE, which will take you to the help page related to the item being selected.
Common Mistakes to Avoid When Writing VBA
Beginners often make some mistakes while writing VBA code. Here are some things to avoid:
- Without Option Explicit, you may not be aware of a typo on the variable name, which can cause errors when the program is run.
- Not using error handling (On Error) can cause the program to stop abruptly if a problem occurs.
- Make sure to use the correct data type when declaring variables. For example, using Integer for large numbers can cause overflow.
- Be sure to check if an object exists before attempting to change its properties. For example, trying to access an ActiveDocument when there is no document open will cause an error.
- Without comments, the code can be difficult to understand both by yourself in the future and by others reading the code.

