Introduction To Vba
Introduction To Vba
TABLE OF CONTENTS
1. Introduction
2. VBA Overview
3. Excel Macros
4. Excel Terms
5. VBA Macro Comments
6. VBA Message Box
7. VBA Input Box
8. VBA- Variables
9. VBA- Constants
10.VBA- Operators
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
With Excel VBA you can automate tasks in Excel by writing so called macros. In this chapter,
we will look at the step-wise procedure to create a simple macro.
To open a VBA window, press "ALT+F11" in your Excel window. The screenshots below
should be able to guide you through the steps.
Step 2: Drill down on ‘Customize the Ribbon’ tab → check 'Developer' tab → Click 'OK'.
(you can locate the Developer tab below the View tab)
*Source: Google
Step 3: You will now see the 'Developer' ribbon in the menu bar
*Source: Google
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
*Source: Google
Step 4: Click the 'Visual Basic' button to open the VBA Editor.
*Source: Google
Step 5: Start scripting by adding a button. To assign a macro (one or more code lines) to the
command button, execute the following steps.
*Source: Google
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
*Source: Google
Step 7: Edit the Name and Caption as shown in the following screenshot.
*Source: Google
Step 8: Now double-click the button and the sub-procedure outline will be displayed as
shown in the following screenshot.
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
*Source: Google
Step 10: Click the button to execute the sub-procedure. The output of the sub-procedure is
shown in the following screenshot.
*Source: Google
In this section, we will discuss the commonly used excel VBA terminologies which we will
encounter in the following sections. Hence it is important to understand them at this stage.
Line of Code
This a VBA instruction as we have seen above. Generally speaking, it performs one task.
Sub
A sub is made up of one or more lines of code. We create a sub so that VBA will process the
instructions we give it. To do this we get VBA to Run the sub. When we “Run” the sub,
VBA goes through all the lines of code and carries out the appropriate actions. A macro and a
sub are essentially the same thing.
Modules
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
Modules is the area where the code is written. A module contains subs which in turn contain
lines of code. There is no reasonable limit to the number of modules in a workbook or the
number of subs in a module that can be created.
*Source: Google
*Source: Google
Within the modules, we can write VBA code and the code is written within a Procedure. A
Procedure is a unit of code enclosed either between the Sub and End Sub statement or
between the Function and End Function statements.
Procedure
Procedures are a group of statements executed as a whole, which instructs Excel how to
perform a specific task. The task performed can be a very simple or a very complicated task.
However, it is a good practice to break down complicated procedures into smaller ones.
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
*Source: Google
Function
A ‘function’ basically takes an input value, performs predefined operations, and returns a
value as a result of the operations. Once a function is typed in the visual basic editor, it will
be available to be called from other VBA procedures or to be used in Excel worksheets. You
need four things in order to declare a function:
For example:
Sub-procedures
These are similar to functions. While sub procedures never Return a value, functions may or
may not return a value. Sub procedures can be called without call keyword. Sub procedures
are always enclosed within Sub and End Sub statements.
It includes details such as developed by, modified by, and can also include incorporated logic.
Comments are ignored by the interpreter while execution.
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
Any statement that starts with a Single Quote (�) is treated as comment. Have a look at the
examples below:
→ This Script is invoked after successful login
→ Written by : HKCareers
→ Return Value : True / False
Any statement that starts with the keyword "REM". Following is an example.
*Source: Google
Like functions and formulas in Excel, the MSGBOX function is how we create a message
box using VBA. Before we start writing VBA code, let’s take a quick look at the syntax
requirements for the MSGBOX function.
Syntax
The syntax of VBA MSGBOX is as follows:
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
Parameter Description
Text_String - This is a Required Parameter. ‘Text_String’ is the message that you want the
msgbox to display. The maximum length of ‘Text_String’ is 1024 characters. If the message
extends to more than a line, then the lines can be separated using a carriage return character
(Chr(13)) or a linefeed character (Chr(10)) between each line.
Buttons - This is an Optional Parameter. A Numeric expression that specifies the type of
buttons to display, the icon style to use, the identity of the default button, and the modality of
the message box. If left blank, the default value for buttons is 0.
Title - This is an Optional Parameter. If the title is left blank, the application name is placed
in the title bar.
Helpfile - This string parameter specifies the help file to be used for the dialog box. It is also
an optional parameter but it becomes mandatory if ‘context’ parameter is to be used.
Context - This is a numeric parameter that specifies the number assigned to the appropriate
Help topic. It is an optional parameter but it becomes mandatory if ‘helpfile’ parameter is
used. If context is provided, helpfile must also be provided.
CONTENT DESCRIPTION
vbOKOnly It displays a single OK button
vbOKCancel It displays two buttons OK and Cancel.
vbAbortRetryIgnore It displays three buttons Abort, Retry, and
Ignore.
vbYesNoCancel It displays three buttons Yes, No, and Cancel.
vbYesNo It displays two buttons Yes and No.
vbRetryCancel It displays two buttons Retry and Cancel.
vbCritical It displays a Critical Message icon.
vbQuestion It displays a Query icon.
vbExclamation It displays a Warning Message icon.
vbInformation It displays an Information Message icon.
vbDefaultButton1 First button is treated as default.
vbDefaultButton2 Second button is treated as default.
vbDefaultButton3 Third button is treated as default.
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
Return Values
The MsgBox function can return one of the following values which can be used to identify
the button the user has clicked in the message box.
# VALUE DESCRIPTION
Example
Function MessageBox_Demo()
'Message Box with just prompt message
MsgBox("Welcome")
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
Step 1: The Function displayed above can be executed either by clicking the "Run" button on
the VBA Window or by calling the function from Excel Worksheet as shown below:-
*Source: Google
Step 2: A Simple Message box is displayed with a message "Welcome" and an "OK" Button
*Source: Google
Step 3: Clicking on OK, displays another dialog box like the one shown below, containing a
message along with "yes, no, and cancel" buttons.
*Source: Google
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
Step 4: After clicking the ‘No’ button, the value of that button (7) is stored as an integer and
displayed as a message box to the user as shown here. Thus the value of the integer indicates
which button the user has clicked on.
*Source: Google
VBA ─ InputBox
This function prompts users to enter values. After entering the values, if the user clicks the
OK button or presses ENTER on the keyboard, the InputBox function will return the text in
the text box. If the user clicks the Cancel button, the function will return an empty string ("").
Syntax
InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context
])
· Title - This is an optional text string that specifies a title to be displayed at the top of
the input box. If the title is left blank, the application name is placed in the title bar.
· Default - This is an optional text string that is displayed in the input box as the default
response if no other response is entered.
· XPos - This optional parameter is an integer specifying (in twips) the horizontal
distance (X axis) of the input box, from the left edge of the screen. If left blank, the
input box is horizontally centered.
· YPos - This optional parameter is an integer specifying (in twips) the vertical distance
of the input box from the top of the screen. If left blank, the input box is vertically
centered.
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
· Helpfile - This too is an optional parameter. It is a string expression that identifies the
helpfile to be used to provide context-sensitive Help for the dialog box.
· Context - This optional parameter is a numeric expression that identifies the Help
context number assigned by the Help author to the appropriate Help topic. If context
is provided, helpfile must be provided as well.
Example 1
This call to the InputBox function displays the following dialog box to the user:
*Source: Google
While the dialog box is displayed, the VBA code pauses, until the user selects one of the
buttons. After the user selects one of the dialog box buttons, the InputBox function returns a
text string, as follows:
→ If the OK button is selected: The text string that has been entered into the dialog box is
returned;
In the above example code, the returned text string is then assigned to the variable response
before the program continues to run.
Example 2
Let us calculate the area of a rectangle by getting values from the user at run time with the
help of two input boxes (one for length and one for width).
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
Function findArea()
Length = InputBox("Enter
Length ", "Enter a Number")
Width = InputBox("Enter
Width", "Enter a Number")
Output
Step 1: In order to execute the above, call using the function name and press Enter as shown
below:-
*Source: Google
Step 2: Upon execution, the First input box (length) is displayed. Enter a value into the input
box.
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
*Source: Google
Step 3: Once you enter the first value, the second input box (width) is displayed:-
*Source: Google
Step 4: Next, click the OK button. The area is displayed as shown in the screenshot below:-
*Source: Google
VBA─VARIABES
Variables are specific values that are stored in a computer memory or storage system. Later,
you can use that value in code and execute. The computer will fetch that value from the
system and show in the output. Each variable must be given a name. Following are the basic
rules for naming a variable.
➢ It must begin with a letter as the first character, and never with a number
➢ No space, period (.), exclamation mark (!), or the characters @, &, $, # in the name is
allowed
➢ The name length cannot can't exceed 255 characters
➢ The Visual Basic reserved keywords cannot be used as variable names
Syntax
In VBA, you need to declare the variables before using them. They can be declared either
explicitly or implicitly
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
❏ Explicitly: Below is an example of variable declared Explicitly. You can use "Dim"
keyword in syntax
❏ Dim Num As Integer
❏ Dim password As String
Data Types
Since the computer cannot differentiate between the numbers (1,2,3..) and strings (a,b,c,..),
Data Types are used to make this differentiation. There are many VBA data types, which can
be segregated into two main categories:
❖ Numeric Data Types
❖ Non-numeric Data Types
This table displays the numeric data types and the allowed range of values.
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
In VBA, if the data type is not specified, it will automatically declare the variable as a
Variant.
Example
Let us create a button and name it as 'Variables_demo' to demonstrate the use of variables.
*Source: Google
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
MsgBox "Password is" & password & Chr(10) & "Value of num is" & num &
Chr(10) & "Value of Birthday is" & BirthDay
End Sub
Output
Once the script is executed, the following output shall be displayed:-
Password is Admin#1
Value of num is 1234
Value of Birthday is 12:02:08 AM
VBA─ Constants
Data whose values do not change within a certain scope should be declared as constants by
using the Const modifier.
The value of a constant is specified when it is declared (this process is called initialization).
Any attempts to alter the value of a constant then results in a compilation error.
Using constants instead of hard-code literal values is an excellent programming practice. This
makes your code more readable and easier to be modified later on if needed.
The rules for naming a constant are same as those for creating variables. The constant must
have a valid symbolic name and an expression composed of numeric or string constants and
operators (but no function calls).
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
➢ No space, period (.), exclamation mark (!), or the characters @, &, $, # can be used in
the name
➢ The name cannot exceed 255 characters in length
➢ You cannot use Visual Basic reserved keywords as variable name
Syntax
In VBA, we need to assign a value to the declared Constants. An error is thrown, if we try to
change the value of the constant.
MsgBox "Integer is " & MyInteger & Chr(10) & "myDate is " &
myDate & Chr(10) & "myDay is " & myDay
End Sub
Output
*Source: Google
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
VBA ─ Operators
The built-in VBA operators consist of mathematical operators, string operators, comparison
operators and logical operators. The different types of Operators are discussed individually
below. VBA supports following types of operators:
❖ Arithmetic Operators
❖ Comparison Operators
❖ Logical (or Relational) Operators
❖ Concatenation Operators
Operato
r Description
+ Adds the two operands
^ Exponentiation operator
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
Dim a As Integer
a=5
Dim b As Integer
b = 10
Dim c As Double
c=a+b
MsgBox ("Addition Result is " & c)
c=a-b
MsgBox ("Subtraction Result is " & c)
c=a*b
MsgBox ("Multiplication Result is " & c)
c=b/a
MsgBox ("Division Result is " & c)
c = b Mod a
MsgBox ("Modulus Result is " & c)
c=b^a
MsgBox ("Exponentiation Result is " & c)
End Sub
Once executed, the above script will display the following results
➔ Addition Result is 15
➔ Subtraction Result is -5
➔ Multiplication Result is 50
➔ Division Result is 2
➔ Modulus Result is 0
➔ Exponentiation Result is 100000
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
Operato Exampl
r Description e
Checks if the value of the two operands are equal or not. If yes, then the
condition ( A == B)
==
is true. False.
Checks if the value of the two operands are equal or not. If the values are not A <> B) is
<>
equal, then the condition is true. True.
(
Checks if the value of the left operand is greater than the value of the right A> B) is
>
operand. If yes, then the condition is true. False.
Checks if the value of the left operand is less than the value of the right (
operand. A< B) is
<
If yes, then the condition is true. True.
Checks if the value of the left operand is greater than or equal to the value of (
the A >= B) is
>=
right operand. If yes, then the condition is true. False.
(
Checks if the value of the left operand is less than or equal to the value of the A <= B) is
<=
right operand. If yes, then the condition is true. True.
These examples discussed here will be helpful towards developing your understanding of
comparison operators:-
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
If a = b Then
MsgBox ("Operator Line 1 : True")
Else
MsgBox ("Operator Line 1 : False")
End If
If a<>b Then
MsgBox ("Operator Line 2 : True")
Else
MsgBox ("Operator Line 2 : False")
End If
If a>b Then
MsgBox ("Operator Line 3 : True")
Else
MsgBox ("Operator Line 3 : False")
End If
If a<b Then
MsgBox ("Operator Line 4 : True")
Else
MsgBox ("Operator Line 4 : False")
End If
If a>=b Then
MsgBox ("Operator Line 5 : True")
Else
MsgBox ("Operator Line 5 : False")
End If
If a<=b Then
MsgBox ("Operator Line 6 : True")
Else
MsgBox ("Operator Line 6 : False")
End If
End Sub
AND If both conditions evaluate to True then the a<>0 AND b<>0 is False
expression is True
XOR Performs logical exclusion on two Boolean (a<>0 XOR b<>0) is False
expressions. If exactly one expression
evaluates to True, but not both, Xor returns
True. If both expressions evaluate to True
or both evaluate to False, Xor returns
False.
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
You can try some of the Logical operators available in VBA by creating a button and adding
the following function.
Dim a As Integer
a = 10
Dim b As Integer
b=0
End Sub
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
When you save it as .html and execute it in the Internet Explorer, then the above script will
produce the following result.
The + Operator has the primary purpose of adding two numbers. However, it can also
concatenate numeric operands with string operands. The + operator has a complex set of rules
that determine whether to add, concatenate, signal a compiler error, or throw a run-time
InvalidCastException exception.
The & Operator is defined only for String operands, and it always widens its operands to
String, regardless of the setting of Option Strict. The & operator is recommended for string
concatenation because it is defined exclusively for strings and reduces your chances of
generating an unintended conversion
Concatenation Operators
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
Following table shows all the Concatenation operators supported by VBScript language.
Assume variable A holds 5 and variable B holds 10, then:-
Example
Here is an example of the Concatenation operator in VBScript:
c=a+b
msgbox ("Concatenated value:1 is " &c) 'Numeric addition
c=a&b
msgbox ("Concatenated value:2 is " &c) 'Concatenate two numbers
End Sub
Below is an example to understand all the Logical operators available in VBA by creating a
button and adding the following function.
Concatenated value:1 is 15
Concatenated value:2 is 510
Concatenation can also be used for concatenating two strings. Check the screenshots below
which represent the Excel & operator and how it can be used as a worksheet function in MS
Excel:
*Source: Google
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching
HKCareers Free Resource
Here are the results that would be returned once we run the string above:-
=A1 & A2
Result: “Alphabet”
Disclaimer:
Data and information above are extracted from the internet and
consolidated by HKCareers. HKCareers does not own the copyrights of the
We help university students to get into Investment Banks, Banks, Property/Conglomerate and Big4s.
Prepared by HKCareers | IG: hkcareers | Facebook: hkcareers | Website: hkcareers.hk/coaching