vba_tutorial 1
vba_tutorial 1
VBA stands for Visual Basic for Applications an event-driven programming language from
Microsoft that is now predominantly used with Microsoft office applications such as MS-Excel,
MS-Word, and MS-Access.
It helps techies to build customized applications and solutions to enhance the capabilities of
those applications. The advantage of this facility is that you NEED NOT have visual basic
installed on our PC, however, installing Office will implicitly help in achieving the purpose.
You can use VBA in all office versions, right from MS-Office 97 to MS-Office 2013 and also
with any of the latest versions available. Among VBA, Excel VBA is the most popular. The
advantage of using VBA is that you can build very powerful tools in MS Excel using linear
programming.
Application of VBA
You might wonder why to use VBA in Excel as MS-Excel itself provides loads of inbuilt
functions. MS-Excel provides only basic inbuilt functions which might not be sufficient to
perform complex calculations. Under such circumstances, VBA becomes the most obvious
solution.
For example, it is very hard to calculate the monthly repayment of a loan using Excel's built-
in formulas. Rather, it is easy to program a VBA for such a calculation.
7
VBA
8
2. VBA ─ Excel Macros VBA
In this chapter, you will learn how to write a simple macro in a step by step manner.
Step 1: First, enable 'Developer' menu in Excel 20XX. To do the same, click File -> Options.
Step 2: Click ‘Customize the Ribbon’ tab and check 'Developer'. Click 'OK'.
9
VBA
Step 4: Click the 'Visual Basic' button to open the VBA Editor.
Step 5: Start scripting by adding a button. Click Insert -> Select the button.
10
VBA
Step 7: Edit the name and caption as shown in the following screenshot.
11
VBA
Step 8: Now double-click the button and the sub-procedure outline will be displayed as shown
in the following screenshot.
12
VBA
Step 10: Click the button to execute the sub-procedure. The output of the sub-procedure is
shown in the following screenshot.
Note: In further chapters, we will demonstrate using a simple button, as explained from
step#1 to 10. Hence , it is important to understand this chapter thoroughly.
13
3. VBA ─ Excel Terms VBA
In this chapter, you will acquaint yourself with the commonly used excel VBA terminologies.
These terminologies will be used in further modules, hence understanding each one of these
is important.
Modules
Modules is the area where the code is written. This is a new Workbook, hence there aren't
any Modules.
To insert a Module, navigate to Insert -> Module. Once a module is inserted 'module1' is
created.
Within the modules, we can write VBA code and the code is written within a Procedure. A
Procedure/Sub Procedure is a series of VBA statements instructing what to do.
14
VBA
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.
Function
A function is a group of reusable code, which can be called anywhere in your program. This
eliminates the need of writing the same code over and over again. This helps the programmers
to divide a big program into a number of small and manageable functions.
Apart from inbuilt Functions, VBA allows to write user-defined functions as well and
statements are written between Function and End Function.
Sub-procedures
Sub-procedures work similar to functions. While sub procedures DO NOT 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.
15
VBA
4. VBA ─ Macro Comments
Comments are used to document the program logic and the user information with which other
programmers can seamlessly work on the same code in future.
It includes information such as developed by, modified by, and can also include incorporated
logic. Comments are ignored by the interpreter while execution.
Any statement that starts with a Single Quote (�) is treated as comment. Following is
an example.
Any statement that starts with the keyword "REM". Following is an example.
16
VBA
5. VBA ─ Message Box
The MsgBox function displays a message box and waits for the user to click a button and
then an action is performed based on the button clicked by the user.
Syntax
MsgBox(prompt[,buttons][,title][,helpfile,context])
Parameter Description
Prompt - A Required Parameter. A String that is displayed as a message in the dialog
box. The maximum length of prompt is approximately 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.
Title - An Optional Parameter. A String expression displayed in the title bar of the
dialog box. If the title is left blank, the application name is placed in the title bar.
Helpfile - An Optional Parameter. A String expression that identifies the Help file to
use for providing context-sensitive help for the dialog box.
4096 vbSystemModal System modal - All applications will not work until the user
responds to the message box.
The above values are logically divided into four groups: The first group (0 to 5) indicates the
buttons to be displayed in the message box. The second group (16, 32, 48, 64) describes
the style of the icon to be displayed, the third group (0, 256, 512, 768) indicates which
button must be the default, and the fourth group (0, 4096) determines the modality of the
message box.
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.
Example
Function MessageBox_Demo()
'Message Box with just prompt message
MsgBox("Welcome")
18
VBA
End Function
Output
Step 1: The above Function can be executed either by clicking the "Run" button on VBA
Window or by calling the function from Excel Worksheet as shown in the following screenshot.
Step 2: A Simple Message box is displayed with a message "Welcome" and an "OK" Button
19
VBA
Step 3: After Clicking OK, yet another dialog box is displayed with a message along with
"yes, no, and cancel" buttons.
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 in the following screenshot. Using this value,
it can be understood which button the user has clicked.
20
6. VBA ─ InputBox VBA
The InputBox function prompts the 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])
Parameter Description
Prompt - A required parameter. A String that is displayed as a message in the dialog
box. The maximum length of prompt is approximately 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.
Title - An optional parameter. A String expression displayed in the title bar of the
dialog box. If the title is left blank, the application name is placed in the title bar.
Default - An optional parameter. A default text in the text box that the user would
like to be displayed.
XPos - An optional parameter. The position of X axis represents the prompt distance
from the left side of the screen horizontally. If left blank, the input box is horizontally
centered.
YPos - An optional parameter. The position of Y axis represents the prompt distance
from the left side of the screen vertically. If left blank, the input box is vertically
centered.
21
VBA
Example
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).
Function findArea()
Dim Length As Double
Dim Width As Double
Output
Step 1: To execute the same, call using the function name and press Enter as shown in the
following screenshot.
22
VBA
Step 2: Upon execution, the First input box (length) is displayed. Enter a value into the input
box.
Step 3: After entering the first value, the second input box (width) is displayed.
Step 4: Upon entering the second number, click the OK button. The area is displayed as
shown in the following screenshot.
23
7. VBA ─ Variables VBA
Variable is a named memory location used to hold a value that can be changed during the
script execution. Following are the basic rules for naming a variable.
You can't use a space, period (.), exclamation mark (!), or the characters @, &, $, #
in the name.
Syntax
In VBA, you need to declare the variables before using them.
Data Types
There are many VBA data types, which can be divided into two main categories, namely
numeric and non-numeric data types.
Byte 0 to 255
24
VBA
Example
Let us create a button and name it as 'Variables_demo' to demonstrate the use of variables.
MsgBox "Passowrd is " & password & Chr(10) & "Value of num is " & num & Chr(10) &
"Value of Birthday is " & BirthDay
End Sub
Output
Upon executing the script, the output will be as shown in the following screenshot.
26
8. VBA ─ Constants VBA
Constant is a named memory location used to hold a value that CANNOT be changed during
the script execution. If a user tries to change a Constant value, the script execution ends up
with an error. Constants are declared the same way the variables are declared.
You can't use a space, period (.), exclamation mark (!), or the characters @, &, $, #
in the 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.
Example
Let us create a button "Constant_demo" to demonstrate how to work with constants.
MsgBox "Integer is " & MyInteger & Chr(10) & "myDate is " & myDate & Chr(10) &
"myDay is " & myDay
End Sub
27
VBA
Output
Upon executing the script, the output will be displayed as shown in the following screenshot.
28
9. VBA ─ Operators VBA
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Concatenation Operators
% Modulus operator and the remainder after an integer division B MOD A will give 0
29
VBA
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
When you click the button or execute the above script, it will produce the following result.
Addition Result is 15
30
VBA
Subtraction Result is -5
Multiplication Result is 50
Division Result is 2
Modulus Result is 0
Checks if the value of the two operands are equal or not. If yes, then the condition (A == B) is
==
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.
Dim a: a = 10
31
VBA
Dim b: b = 20
Dim c
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
32
VBA
If a<=b Then
MsgBox ("Operator Line 6 : True")
Else
MsgBox ("Operator Line 6 : False")
End If
End Sub
When you execute the above script, it will produce the following result.
Called Logical AND operator. If both the conditions are True, then the a<>0 AND b<>0 is
AND
Expression is true. False.
Called Logical OR Operator. If any of the two conditions are True, then the a<>0 OR b<>0 is
OR
condition is true. true.
Called Logical NOT Operator. Used to reverse the logical state of its operand. NOT(a<>0 OR
NOT
If a condition is true, then Logical NOT operator will make false. b<>0) is false.
33
VBA
Called Logical Exclusion. It is the combination of NOT and OR Operator. If (a<>0 XOR b<>0)
XOR
one, and only one, of the expressions evaluates to be True, the result is True. is false.
Else
MsgBox ("AND Operator Result is : False")
End If
34
VBA
Else
MsgBox ("XOR Operator Result is : False")
End If
End Sub
When you save it as .html and execute it in the Internet Explorer, then the above script will
produce the following result.
Note: Concatenation Operators can be used for both numbers and strings. The output
depends on the context, if the variables hold numeric value or string value.
Concatenation Operators
Following table shows all the Concatenation operators supported by VBScript language.
Assume variable A holds 5 and variable B holds 10, then -
35
VBA
Example
Try the following example to understand the Concatenation operator available 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
Try the following example to understand all the Logical operators available in VBA by creating
a button and adding the following function.
Concatenated value:1 is 15
Concatenation can also be used for concatenating two strings. Assume variable A =
"Microsoft" and variable B = "VBScript" then -
Example
36
VBA
Try the following example to understand all the Logical operators available in VBA by creating
a button and adding the following function.
c=a+b
msgbox("Concatenated value:1 is " &c) 'addition of two Strings
c=a&b
msgbox("Concatenated value:2 is " &c) 'Concatenate two String
End Sub
When you save it as .html and execute it in the Internet Explorer, then the above script will
produce the following result.
37
VBA
38