MsExcel VBA Course Material
MsExcel VBA Course Material
Developed by
Sanjay Jamalpur
1
MsExcel VBA
Table of Contents
Macro _________________________________________________________________________ 4
Record a macro _________________________________________________________________ 4
Running a Recorded Macro ________________________________________________________ 5
Deleting a Macro ________________________________________________________________ 5
Editing the recorded macro ________________________________________________________ 6
Introduction to VBA ______________________________________________________________ 7
Object Models __________________________________________________________________ 7
Understanding the Visual Basic Editor _______________________________________________ 8
Working with Project Explorer _____________________________________________________ 9
Understanding Sub Procedure and Function Procedure ________________________________ 11
Understanding Data Types, Variables and Constants __________________________________ 13
Variable ______________________________________________________________________ 14
Constants _____________________________________________________________________ 15
Operators _____________________________________________________________________ 15
Arithmetic Operators ___________________________________________________________ 15
Comparison (Relational) Operators ________________________________________________ 16
Logical Operators ______________________________________________________________ 17
Understanding the Document Object Model (DOM) of Excel ____________________________ 18
Using With-End With construct____________________________________________________ 20
Decision making using IF-Then constructs ___________________________________________ 21
Select Case construct ____________________________________________________________ 22
Looping ______________________________________________________________________ 23
InputBox ______________________________________________________________________ 26
MsgBox Function _______________________________________________________________ 27
String Functions ________________________________________________________________ 28
Date Functions _________________________________________________________________ 29
Creating Custom Menu / Toolbar (Excel 2003) _______________________________________ 30
Adding Icons on Quick Access Toolbar (Excel 2007/2010/2013) __________________________ 32
Creating own custom Tab on the Ribbon (Excel 2010 / 2013) __________________________ 33
Excel (DOM) Objects and Properties ________________________________________________ 34
Chart Objects and Properties _____________________________________________________ 34
PageSetup Objects and Properties _________________________________________________ 34
Font Objects and Properties ______________________________________________________ 35
Characters Object ______________________________________________________________ 35
2
MsExcel VBA
3
MsExcel VBA
Macro
A macro is a set of instructions, which can be called number of times to ease a repetitive task.
The instructions called statements are written on a macro sheet in the Visual Basic language.
Record a macro
1. On the View tab, point to Macro, and then click Record New Macro.
2. In the Macro name box, enter a name for the macro.
Note: The first character of the macro name must be a letter. Other characters can be letters,
numbers, or underscore characters. Spaces are not allowed in a macro name; an underscore
character works well as a word separator.
3. To run the macro by pressing a keyboard shortcut key, enter a letter in the Shortcut key box.
You can use CTRL+ letter (for lowercase letters) or CTRL+SHIFT+ letter (for uppercase letters),
where letter is any letter key on the keyboard. The shortcut key letter you use cannot be a
4
MsExcel VBA
number or special character such as @ or #. The shortcut key will override any default
Microsoft Excel shortcut keys while the workbook that contains the macro is open.
4. In the Store macro in box, click the location where you want to store the macro.
If you want a macro to be available whenever you use Excel, store the macro in the Personal
Macro Workbook in the Excel Startup folder.
To include a description of the macro, type the description in the Description box.
5. Click OK.
If you select cells while running a macro, the macro will select the same cells regardless of
which cell is first selected because it records absolute cell references. If you want a macro
to select cells regardless of the position of the active cell when you run the macro, set the
macro recorder to record relative cell references. On the Stop Recording toolbar, click
Relative Reference. Excel will continue to record macros with relative references until you
quit excel or until you click Relative Reference again.
6. Carry out the actions you want to record.
7. On the Macro button, click Stop Recording
Deleting a Macro
Select the View tab click on the Macro button choose View Macro this will pop up the
above dialog box select the macro you want to delete and click on Delete button.
5
MsExcel VBA
6
MsExcel VBA
Introduction to VBA
Visual basic for application (VBA) is a powerful programming language that you can use to add
automation, new features, or even customized functions to your excel workbooks.
Object Models
The secret of using VBA with other application lies in understanding the object model for each
application. Excels object model for example exposes several very powerful data analysis objects,
such as worksheets, charts, pivot tables and scenarios as well as mathematical, financial,
engineering and general functions. With VBA, you can work with these objects and develop
automated procedures. Object classes are arranged in a hierarchy the arrangement of these objects
is referred to as Excels Object Model. As explained below with an example.
The above statement means as follows Application refers to the main object i.e. MS Excel which
contains another object as WorkBooks and Book1 is the name of the workbook, which in turn
consists of Worksheet object and Sheet1 is the name of the sheet, which in turn consist of cells which
is defined by Range object and Select is a method or action to be done. In short to describe the
above object hierarchy selects cell A1 in worksheet by name Sheet1 present in workbook (file) by
name Book1
7
MsExcel VBA
The above fig. shows the VBE chances are that your VBE window may not look exactly as above
because this is highly customizable, you can hide windows, change their sizes, dock them,
rearrange them and so on.
The VBE has lots of parts lets briefly understand some key components
Menu bar
The VBE menu bar works like any other menu bar youve in windows based programmes. It contains
commands that you use to work with the various components in the VBE.
Toolbar
The standard toolbar is directly under the menu bar by default. VBE toolbars work just like those in
Excel. For displaying the toolbars click on menu View Toolbars Select the required toolbar
8
MsExcel VBA
Code window
A code window (sometimes known as a module window) contains VBA code. Every item in a project
has an associated code window. To view a code window for an object, double-click the object in the
Project Explorer window on the required object / module
Immediate window
The immediate window is most useful for executing VBA statements directly, testing statements,
and debugging the code. This window may or may not be visible. If the immediate window is not
visible, then press CTRL + G
When youre working in the VBE, each excel workbook and add-in thats currently open is
considered a project. You can think of a project as a collection of objects arranged as an outline. You
can expand a project by clicking the plus sign (+) at the left of the projects name in the Project
Explorer window. You can contract a project by clicking the minus sign (-) to the left of a projects
name, above fig. shows the Project Explorer.
9
MsExcel VBA
Exporting objects
Every object in a project can be saved to a separate file. Saving an individual object in a project is
known as Exporting. And it stands to reason that you can also Import objects into a project. Exporting
and Importing objects might be useful it you want to use a particular object (such as VBA module or
a UserForm) in a different project. To export an object select it in the Project Explorer window and
choose File Export File (Or press Ctrl + E) you will be prompted for a file name.
Note: If you export that object remains in the project (only a copy of it is exported).
Importing objects
To import a file into a project select the projects name in the Project Explorer window and choose
File Import File you will be prompted with a dialog box asking for file name. You can import only
a file that has been exported using File Export command.
10
MsExcel VBA
Sub Procedure
Function Procedure
Sub Procedure Sub Procedure is a set of instructions given to perform certain task in logical
sequence, a sub procedure does not return value and it may or may not carry the arguments.
End Sub
The keyword Sub defines the start of the procedure and End Sub marks the end of procedure and
the open close parentheses () may or may not contain arguments. ProcedureName is the valid
procedure name and the program (code) is written in between the Sub and End Sub.
Function Procedure Function Procedure is a set of instructions given to perform certain task in
logical sequence; a function procedure returns value and carries required number or arguments. It
can return only one value at one time.
General syntax of Function Procedure
Function FunctionName (Arg1 as type, Arg2 as type..) as type
--------
Executable statements
--------
End Function
The keyword Function defines the start of the function and End Function marks the end of function
and the open close parentheses () contain arguments (Arg1 as type, Arg2 as type) the
arguments are defined with their respective data type as type is the return value data type.
FunctionName is the valid function name and the program (code) is written in between the Function
and End Function.
11
MsExcel VBA
Procedure / Function name should start with an alphabet and can contain number and
underscore
Procedure / Function name cannot contain any defined library keyword
Procedure / Function name should be unique
Procedure / Function name can be maximum 255 characters long (including text, number and
underscore)
Procedure / Function name cannot contain any special character like %, $ etc.
12
MsExcel VBA
Data types
13
MsExcel VBA
Variable
A variable is simply a named storage location in computers memory. Variables can accommodate a
wide variety of data types from simple Boolean values (True or False) to large double precision
values. You can assign values to the variable by using the equal sign operator. And the value assigned
to the variable can change in the course of program.
Declaring Variable
Variable is declared by using keyword Dim and Public along with data type. Below examples show
declaring of variable
Variable declared by using Dim keyword is a Local variable which is accessible within the procedure
it is declared
Variable declared by using Public keyword is a Global variable which is accessible across all the
procedures, forms and modules.
Below statements show declaring multiple variables of different data types and assigning values to
them
Dim Length as Single
Dim Name as String
Dim Breadth as Integer
Length = 2.4
Name = MsExcel
Breadth = 6
Note: If you dont declare variable name with specific data type VB considers that to be of Variant
data type
14
MsExcel VBA
Constants
A variables value may and often does, change while a sub procedure or function is executing (thats
why its called a variable). Sometimes you need to refer to a named value or string that never
changes.
Declaring constants
You declare constants using the Const statement. As shown below in examples
Const PI as Single = 3.142
Const Name as String = MsExcel
Note: If you attempt to change the value of a constant in VBA, you get an error, which is what you
would expect. A constant is a constant not a variable.
Operators
The operators used in VBA are classified as follows
Arithmetic
Comparison (Relational)
Logical
Arithmetic
operator Meaning Example
+ (plus sign) Addition 3+3
(minus sign) Subtraction 31
Negation
* (asterisk) Multiplication 3*3
/ (forward slash) Division 3/3
MOD Returns the remainder 5 MOD 2 returns 1
^ (caret) Exponentiation 3^2 (the same as 3*3)
15
MsExcel VBA
Comparison (Relational) Operators: You can compare two values with the following operators.
When two values are compared by using these operators, the result is a logical value, either TRUE
or FALSE.
Comparison
operator Meaning Example
= (equal sign) Equal to A=B
> (greater than sign) Greater than A>B
< (less than sign) Less than A<B
>= (greater than or equal to sign) Greater than or equal to A>=B
<= (less than or equal to sign) Less than or equal to A<=B
<> (not equal to sign) Not equal to A<>B
Text concatenation operator Use the ampersand (&) to join, or concatenate, one or more text
strings to produce a single piece of text.
Text
operator Meaning Example
& (Ampersand) Connects, or concatenates, two values to "North" & "wind" produce
produce one continuous text value "Northwind"
Reference operators Combine ranges of cells for calculations with the following operators.
Reference
operator Meaning Example
: (Colon) Range operator, which produces one reference B5:B15
to all the cells between two references,
including the two references
, (Comma) Union operator, which combines multiple Dim Area, Peri, Volume as
references into one reference Single
16
MsExcel VBA
Logical
operator Meaning
AND Used for testing if two or more than
conditions are satisfied
OR Used for testing if either one of the
condition is satisfied
NOT Used for testing if the condition is not
satisfied.
17
MsExcel VBA
18
MsExcel VBA
Clicking on the option Microsoft Excel Object Model Reference this will pop-up the Microsoft Excel
Object Model dialog box as shown below
For accessing any of the object with its properties click on that object for e.g. for accessing the Font
object click on the Font link and this will the font object properties dialog box as shown below
19
MsExcel VBA
To start understanding how the With-End With construct works lets examine the following
procedure, which modifies the properties of selected data.
Sub Format_Data ()
Selection.Font.Name=Arial
Selection.Font.Size=12
Selection.Font.Color=vbBlue
Selection.Font.Bold=True
End Sub
This procedure can be rewritten using the With-End With construct. The following procedure
performs exactly same operations like the preceding one.
Sub Format_Data ()
With Selection.Font
.Name=Arial
.Size=12
.Color=vbBlue
.Bold=True
End With
End Sub
The procedure that uses With-End With statement for changing the properties of the selected data
works significantly faster than the equivalent procedure that explicitly references the object in each
statement.
20
MsExcel VBA
If condition Then
-------
Executable Statements
-------
Else
-------
Executable Statements
-------
End If
If-AND construct
21
MsExcel VBA
If-OR construct
If condition Then
Executable Statements
ElseIf condition Then
Executable Statements
ElseIf condition OR condition Then
Executable Statements
ElseIf condition AND condition Then
Executable Statements
Else
Executable Statements
End If
22
MsExcel VBA
Looping
Looping is the process of repeating a block of instructions. You may know the number of times to
loop, or it may be determined by the values of variables in your program.
For Loop is used to repeat set of instructions with specified start and end point
General syntax of for loop
The above program is going to print numbers from 1 to 10 columns wise incrementing every time
by one.
Sub ForDemo ()
Dim i As Integer
For i = 1 To 10 Step 2
ActiveCell.Offset(0, i) = i
Next i
End Sub
The above program is going to print numbers between 1 to 10 column wise incrementing every time
by 2
23
MsExcel VBA
For Each Next loop repeats a block of statements for each object in collection. VBA
automatically sets the variable each time the loop runs.
General syntax of for each next loop
Sub ChangeCase()
For Each Cell In Selection
If Application.WorksheetFunction.CountBlank(Cell) = 0 Then
Cell.Value = UCase(Cell.Value)
End If
Next
End Sub
In the above example the CountBlank () function checks each cell in selection whether it is empty or
not if not then it converts the case of the text to upper case and the task is repeated for each cell in
selection.
Do-While Loops
A Do-While loop is another type of looping structure available in VBA. Unlike a For-Next loop, a Do-
While loop executes while a specified condition is met.
There are two forms of Do-While loop they are as follows
1)
Do While Condition
-------
Executable Statements
-------
Loop
2)
Do
--------
Executable Statements
--------
Loop While Condition
Note: In the first form of Do-While loop the condition is checked first and then the statements are
executed this is also called as Entry Control loop.
24
MsExcel VBA
Note: In the second form of Do-While loop once the statements are executed and then the condition
is checked this is also called as Exit Control loop.
The following example uses a Do-While loop with the first syntax
Sub DoWhileLoop ()
Do While IsEmpty(ActiveCell)
ActiveCell.Value = 0
ActiveCell.Offset(1, 0).Select
Loop
End Sub
The above procedure uses the active cell as the starting point and then travels down the column,
inserting a zero into the active cell. Each time the loop repeats, the next cell in the column becomes
the active cell. The loop continues until VBAs IsEmpty function determines that the active cell is not
empty.
25
MsExcel VBA
VBA provides many build in functions like String, Date/Time, Math, Input, Output etc. Few of them
which are used very frequently in day to day work are listed below.
InputBox Displays a dialog box for user input. Returns the information entered in the dialog box.
Use InputBox to display a simple dialog box so that you can enter information to be used in a macro.
The dialog box has an OK button and a Cancel button. If you choose the OK button, InputBox returns
the value entered in the dialog box. If you click the Cancel button, InputBox returns False.
Default Value Specifies the value that will be displayed in the text box when the dialog box pops
up.
VariableName After entering the value in the box when you press OK button it is stored in the
variable.
26
MsExcel VBA
MsgBox Function
The MsgBox function is one of VBAs most useful functions. It is often used as a good substitute for
a simple custom dialog box. Its also an excellent debugging tool because you can insert MsgBox
function at any time to pause your code and to display the result of a calculation or assignment.
VB-Button A value that specifies which buttons to appear in the message box, use built in
constants for example VBYesNo
27
MsExcel VBA
String Functions
String functions are used for editing, manipulating and extracting textual data. Some of the very
frequently required string functions are as follows.
Strconv (String Expression, Conversion Factor) converts the string to upper / lower / proper case.
Conversion Factor 1 / 2 / 3
Trim (String Expression) removes the redundant blank space before and after the string.
Strcomp (String1, String2, Compare) Used for comparing two strings and returns a Integer
indicating the result of comparison.
InStr (Start, String1, String2, Compare) returns the position of first occurrence one string within
another.
Left (String Expression, No of Chars) returns specified number of characters from left side of
string
Right (String Expression, No of Chars) returns specified number of characters from right side of
string
Mid (String Expression, Start, No of Chars) returns specified number of characters from the string
with given start point and length
28
MsExcel VBA
InStrRev (Source String, String to search, Start, Compare) returns the position of character in
the string from end of string
Note: Specifying the start as -1 starts the search from end of string
Date Functions
Date functions are used for editing, manipulating and extracting date. Date is internally stored as
number starting from 1st Jan 1900 till 31st Dec 9999. Some of the very frequently required date
functions are as follows.
29
MsExcel VBA
Excel allows us to create custom menu and toolbar and assign the procedures we have written in
VBA to them for easy access.
Following are the steps we should follow to create custom menu bar
1. Click on menu View Toolbars Customize This will pop-up the Customize dialog box as
shown below
2. Click on the Commands tab and under Categories choose New Menu
3. Drag and drop the New Menu option Under Commands: besides any of excels menus
4. Then right click mouse on the new menu and specify an appropriate name for the menu
5. Now for inserting commands in the new menu click on Macros option under Categories
6. This will show the Macro options as whown below in the diagram.
7.
30
MsExcel VBA
8. Drag and drop the Custom Menu Item from Commands: into the new menu created.
9. After dropping it right click mouse on it and rename as per requirement. And assign macro to
the new element by clicking on option Assing Macro
10. After clicking on Assign Macro option the Macro dialog box pops up select the macro name
you would like to assign and close the dialog box.
11. Repeat steps 8 to 9 untill you finish assigning the commands.
31
MsExcel VBA
Click on the drop down arrow on Quick Access Toolbar and Select More Commands as
shown below in the image
This will pop-up the Excel Options dialog box as shown below
32
MsExcel VBA
Click on the drop down arrow on Quick Access Toolbar and Select More Commands
OR
Click on File button and choose Options this will pop-up the Excel Options dialog
box as shown below
Choose Customize Ribbon on the left pane and under Choose commands from choose
Macros
Click on the New Tab button for creating a new tab and rename it by clicking on the
Rename button
Click on New Group button to create a new group and rename it by clicking on Rename
button
Select the Macro to populate in the group and click on the button Add>>
Once done click on OK button
33
MsExcel VBA
PageSetup.RightMargin=Application.inchestoPoints(0.5)
Used for setting the Left/Right/Top/Bottom
margins
PageSetup.TopMargin=Application.inchestoPoints(0.5)
PageSetup.BottomMargin=Application.inchestoPoints(0.5)
34
MsExcel VBA
Characters Object
Characters (Start, No of Chars) Used for modifying characters in the string with specified Start
point and number of characters
35
MsExcel VBA
Shapes.AddPicture File Name, Link to File, Save with Document, Left, Top, Width, Height
DIR function: returns a string representing the name of a File, Directory or Folder that matches
a specified pattern or file attribute
36
MsExcel VBA
Cells, Worksheet, Workbook, Selection, Copy, Paste, Windows Objects and Properties
37