Visual Basic for Applications
Introduction
VBA stands for Visual Basic for Applications. It is a programming language developed by Microsoft that is integrated into various Microsoft Office applications, such as Excel, Word, PowerPoint, and Access. VBA allows users to automate tasks, create custom functions, and enhance the functionality of Office applications by writing scripts or macros.
VBA code is written within the Office application environment and can access the application's object model, allowing for direct manipulation of elements such as worksheets, cells, documents, slides, and more. This makes VBA a versatile tool for a wide range of tasks, from simple data manipulation to complex automation workflows.
Set up
To be able to code within Excel in VBA, you need to have the Developer tab.
If you don't have it:
- Go to the tab
File
; - Click on
Options
; - Click on
Customize Ribbon
; - On the right, in the Main Tabs, select
Developer
; - Click on
OK
.
Now you can go to the tab Developer
:
- Click on
Visual Basic
to open the editor; - Click on
Insert
and then selectModule
; - There you can write your VBA code.
First example
- Write the following code in an empty VBA module:
- Click the
Run Sub
button - Check the result in the
Intro VBA
sheet.
Modify a cell
To modify a cell in a specific sheet:
Your content can be a known value or it can be a reference to a different cell.
Example
Conditional
The syntax for the conditional in VBA is the following:
If condition Then
processing
ElseIf condition Then
processing
Else
processing
End If
Let's do a concrete example:
Example
Help for the project
To check if a cell is not empty, you can write:
Loop
The syntax for the loop in VBA is the following:
Let's do a concrete example:
Example
Sorting Data
When sorting using VBA, you need to use the Range.Sort
method.
The Range
would be the data that youβre trying to sort. For example, if youβre sorting the data in A1:A10
, then Range
would be Range(βA1:A10β)
.
With the sort method, you need to provide some additional information through parameters. Below are the key parameters you need to know:
- Key β here you need to specify the column that you want to sort. For example, if you want to sort column A, you need to use
key:=Range(βA1β)
- Order β here you specify whether you want the sorting in an ascending order or the descending order. For example, if you want the sorting in ascending order, you will use
Order:=xlAscending
- Header β here you specify whether your data set has headers or not. If it has headers, the sorting starts from the second row of the data set, else it starts from the first row. To specify that your data has headers, you will use
Header:=xlYes
1. Single Column Without Header
2. Single Column With Header
3. Sorting Multiple Columns With Headers
Clearing Data
You can clear data in VBA using the ClearContents
method. You only have to specify the range that you want to clear.
For example: