You are on page 1of 39

Introduction to VBA –

Macros Programming
Job oriented training program
crafted by experts

Disclaimer: This material is protected under copyright act AnalytixLabs ©, 2011-2015. Unauthorized use and/ or duplication of this material or any part of this material
including data, in any form without explicit and written permission from AnalytixLabs is strictly prohibited. Any violation of this copyright will attract legal actions

Learn to Evolve
Contents - Session 1
 Key components of a programming language
⁻ Keywords & Syntax
⁻ Programming Statements
⁻ Variables
⁻ Data Types
⁻ Comments
⁻ Operators
 A look at some commonly used code snippets
 Case Study 1 – Explaining the problem statement
 Programming constructs in VBA
⁻ The With…End With block
 Case Study – Macro Recording Demo and Code Walk-through

2
Contents - Session 2
 Programming constructs in VBA (contd.)
⁻ Control Structures
⁻ Looping Structures
 Functions & Procedures in VBA – Modularizing your programs
 Objects & Memory Management in VBA
⁻ The NEW and SET Keywords
⁻ Destroying Objects - The Nothing keyword
 Controlling accessibility of your code – Access specifiers
 Code Reusability – Adding references and components to your code
 Practice Exercises & Case Study 2

3
Contents

1 Key components of a programming language

2 Commonly used code snippets

3 Programming constructs in VBA


Key components of VBA – Keywords & Syntax
Every programming language contains two main components that make up its core : Keywords and syntax.

It helps to understand that all programming languages are artificial languages and hence imitate human languages in several ways.

Components of a Human language Components of a Programming language


E.g. for illustration : English E.g. for illustration : Visual Basic

The English Dictionary The Visual Basic Keywords

The English Grammar The Visual Basic Syntax

Tip:
In the code window, syntax errors
show up in red and all keywords
show up in blue colour.

5
Key components of VBA – Programming statements
A statement in a programming language is the same as a sentence in a human language.

So a statement essentially refers to a “single line of code” and is the smallest unit into which a program can be broken down to. Every
statement accomplishes a certain task in the program and must confirm to the syntax rules of the language.

A few VBA statement examples are listed below :

Dim rowCtr as Integer Sheet16.Name = “Raw Data”


Sheet1.Range(“A6”).Value = 66.223 Sheet12.AutoFilterMode = False

Tip:
A key point to note here is that unlike other
languages, VBA does not use a line
terminating character.

6
Key components of VBA - Variables
A variable is a temporary location in your computer’s memory where values can be stored. All such temporary locations must be assigned a
unique name by the programmer before they can be used.

Key rules governing variables in VBA –


 Variable names must start with an alphabet and can only be composed of alphabets, numbers and underscores.
 Keywords cannot be used as variable names (eg: add, data, etc)
 All variables must confirm to a Data-Type of the programing language

The “Dim” statement in VBA is used to declare a variable. The Syntax for this statement is listed below :
Dim <variableName> as <Data-Type> [, <variableName> as <Data-Type>, ...]

A few examples :

Dim iCtr as Integer Dim username as String, usrPwd as String

Dim loopCounter as byte Dim errorFoundFlag as Boolean

7
Key components of VBA - Data Type
A Data-Type is variable classification that denotes and controls the type of data can be stored in the variable. Each variable must be assigned a Data-Type
at the time of its declaration, any attempts to assign a value to the variable not confirming to its Data-Type will result in an error. The table below lists all the
data types that are available to the programmer in VBA :

Data Type Storage Size Range

Byte 1 byte 0 to 255


Boolean 2 bytes True or False
Integer 2 bytes -32768 to 32767
Long 4 bytes -2147483648 to 2147483647
-3.402823E38 to -1.401298E-45
Single 4 bytes
1.401298E-45 to 3.402823E38
-1.79769313486232E+208 to 4.94065645841247E-324 (for negative value)
Double 8 bytes
4.94065645841247E-324 to 1.79769313486232E+208 (for positive value
Currency 8 bytes -922337203685477.5808 to 922337203685477.5807
Date 8 bytes January 1,1900 to December 31, 9999
Object 4 bytes Any object reference

String (variable length) 10 bytes + string length 0 to 2 billion approx


String (fixed length) Length of string 1 to 65400 approx
Variant (with number) 16 bytes same as double data type
Variant (with Chars) 22 bytes + string length same range as length of string

8
Key components of VBA - Comments
Comments in VBA (and in any other programming language as well) serve two purposes -
a)Allow the programmer to change one or more programming statements into non-executable code, and
b)Do inline documentation of the code i.e. leave notes and explanations on what the code is doing.

All comments start with a single quote (‘) and will show up in green colored text in the Code window. This gives us the flexibility that a comment
can even start from the middle of a line in your program.

A few examples of how to use comments in VBA are shown below :

Public Sub doBrowse (dialogType As String) ...


For iCtr = 1 to fileCount
‘Procedure to show the user a Browse dialog ‘Looping once for each file
‘box. Needs dialogType as an argument which If fileName = “” Then ‘Missing value check
‘can be either “File” ‘or “Folder”. Msgbox “Invalid File Name.”
‘Written by James Smith, 29-may-2012. Exit For
End If
Dim fileCount As Integer ...
... ...

Example of multiline comment at the top of a block of code Examples of single line comments in code (in-line comments)

9
Key components of VBA - Operators
Operators are keywords (words or symbols) that allow us to do mathematical, logical or other types of operations. VBA has 4 types of operators:

Arithmetic operators
+ The addition operator
Used to add numeric expressions, as well as to concatenate (join together) two string variables. However, it’s preferable to use the
concatenation operator with strings to eliminate ambiguity.
Example: total = expense1 + expense2

– The subtraction operator


Used to find the difference between two numeric values or expressions, as well as to denote a negative value. Unlike the addition operator, it
can’t be used with string variables.
Example: idiff = iOld_Value – iNew_Value

/ The division operator.


Returns a floating-point number. Example: sngNoOfShares = sngTotalVal / sngUnitPrice

* The multiplication operator.


Used to multiply two numerical values. Example: iSale_Val = iQuant * iPrice

\ The integer division operator.


Performs division on two numeric expressions and returns an integer result (no remainder or decimal places). Example: iTotFTE = iTotalBill \
iPerDiem

10
Key components of VBA - Operators
Arithmetic operators (Contd.)
^ The exponentiation operator.
Raises a number to the power of the exponent. Example: result = number ^ exponent

Mod The modulo operator.


Performs division on two numeric expressions and returns only the remainder. If either of the two numbers is floating-point, it’s
rounded to an integer value prior to the modulo operation. Example: iRem = iNum1 Mod iNum2

Concatenation operator
& The Concatenation operator.
It’s used to bind a number of string variables together, creating one string from two or more individual strings.
Example: result = sExpression1 & sExpression2

Logical Operators
And (Logical conjunction operator) Checks for logical AND i.e. true if both the expressions are True.
E.g. If x = 27 And y = 48 then

Or (Logical disjunction) Checks for logical OR i.e. True if any of the two or both expressions are True.
E.g. If x = 27 Or y = 48 then

11
Key components of VBA - Operators
Logical Operators (Contd.)
Not (Logical negation) performs logical Not on one expression. i.e. if the expression is True, Not, makes it False.
E.g. If Not IsNumeric(x) Then

Comparison Operators
= (Equals To) Check for equality
E.g. Debug.print iXvalue = iYvalue

< (Less Than)


Example: if iXvalue < iYvalue then Debug.print “It is Less”

> (Greater Than)


Example: if iXvalue > iYvalue then Debug.print “iXvalue is higher”

The above listed operators can be used in combinations to get to more conditions as listed below :
>= (Greater than or equal to)
<= (Less than or equal to)
<> (Not equal to)

12
Key components of VBA - Operators
Order of Precedence
This is the order in which VBA will evaluate If more than one operator is in a single line of code.

Order among the different types of operators : Within arithmetic operators, the sequence of evaluation is :

 Arithmetic operators Exponentiation (^)


 Concatenation operators  Division and multiplication (/, *) (no precedence between the two)
 Comparison operators  Integer division (\)
 Logical operators  Modulo arithmetic (Mod)
 Addition and subtraction (+, –) (no precedence between the two)

...
If ( iCtr>=4 AND Sheet2.Range(“A6”).Value = iCtr + (23 * rowCount) ) OR ( iCtr<4 ) Then
...

Example of an “IF” statement with multiple types of operators used in the same expression

13
Contents

1 Key components of a programming language

2 Commonly used code snippets

3 Programming constructs in VBA


Some code snippets - commonly needed tasks
Task Example Statement(s)
Putting value in a cell (e.g. A6 on Sheet2) Sheet2.Range(“A6”).Value = 33, or
Sheet2.Range(“A6”).Value = userName, or
Sheet2.Range(“A6”).Value = “Result: “ & calcResult
Reading value of a cell (e.g. from cell B23 on usrInput = Sheet6.Range(“B23”).value
Sheet6)
Activating a cell on a sheet Sheet3.Range(“A5”).Activate
Selection cell(s) on a sheet Sheet3.Range(“A2:B16”).Select
Activating a sheet Sheet6.Activate
Putting a formula in a cell Sheet3.Range(“A5”).Formula = “=Sum(A23:D45)”
Accessing a cell using offset (e.g. 1 – E.g. 1 – Sheet2.Range(“A3”).Offset(2,0).Value = 23
Accessing a cell 2 rows below; e.g. 2 – (Reaching cell A5)
Accessing a cell 1 row above and 3 columns
right) E.g. 2 – Sheet3.Range(“B23”).Offset(-1, 3).Value = 44
(Reaching cell E22)

Showing a message to the user Msgbox “Program Execution Completed.”


Accepting input from a user (not using the usrInput = InputBox(“Please enter your name”)
cells of a sheet)
Copying a cell(s) and doing a Paste-Special- Sheet2.Range(“A3”).Copy, or Sheet2.Range(“A3:A65”).Copy
Values on another Sheet2.Range(“B65”).PasteSpecial xlPasteValues
Deleting everything from a cell(s) Sheet2.Range(“A2”).ClearContents, or
Sheet2.Range(“A2:B65”).ClearContents

15
Our case study for this session
Our first case study involves formatting a table of data to bring it to presentable form (as shown below). Key points to focus on in this case will be :
a) How to record macros in Excel
b) How to ensure recoded macros are re-usable and not context dependent
c) Interpreting recorded macros based on what we’ve learnt so far

Our starting point will be this data table from the


AnalytixLabs Excel training workbook.

The output we’re aiming for is the formatted version of this


table shown below.

Process : We will be recording all the formatting steps and


will thereafter understand & modify the recorded code to
ensure it is clean & re-usable.

16
Contents

1 Key components of a programming language

2 Commonly used code snippets

3 Programming constructs in VBA


Programming constructs in VBA – “With….End With” Block

There are situations where we are required to write several statements that act on the same object. The With…End With block is used to
make this type of code more efficient and easier to read.

Syntax :
With <Object Name>
<statements>
End With

Example :
Activesheet.Range(“C9”).Interior.ColorIndex = 3 The code snippet is working on the same object in all
Activesheet.Range(“C9”).Font.Bold = True the 4 statements (Range C9 of the Active Sheet)
Activesheet.Range(“C9”).Font.ColorIndex = 3
Activesheet.Range(“C9”).Font.Size = 14

With Activesheet.Range(“C9”)
.Interior.ColorIndex = 3
The same code with the use of the With…End With
.Font.Bold = True construct
.Font.ColorIndex = 3
.Font.Size = 14
End With

18
Let’s look at our case study
Important keyboard shortcuts to remember as we switch over to the VBA IDE

Task Shortcut
Opening the VBA IDE ALT + F11
Opening the Immediate Window CTRL + G
Executing code in normal mode F5
Executing code in debug mode (one line at a F6
time)
Executing a pre-written macro in a file from ALT + F8
the Worksheet interface

19
End Of Session 1

20
Contents

1 Programming constructs in VBA

2 Functions & Procedures in VBA – Modularizing your programs

3 Objects & Memory Management in VBA

4 Controlling accessibility of your code – Access specifiers

Code Reusability – Adding references and components to your


5 code
Programming constructs – Control Structures
There are two options to choose from to execute statements based on a condition

If … Then … Else – These statements allow us to execute one or Select .. Case – complex If..Then..Else statements can be rewritten
more lines of code based on one or more conditions. using a Select…Case statement which is simpler to read.

Syntax : If <condition> Then Syntax : Select Case <TestExpression>


<statements> Case <Expressionist>
ElseIf <condition> Then <statements>
<statements> Case Else
Else <statements>
<statements> End Select
End If

Example : If iNum = 1 then Example : Select case iNumber


Msgbox “One” Case 1
ElseIf iNum = 2 Or iNum = 3 then Msgbox “One”
Msgbox “Two or Three” Case 2, 3
Else Msgbox “Two or Three”
Msgbox “Num not in range.” Case Else
End If Msgbox “Num not in range.”
End Select
If..Then..Else structure can be replaced with a Select..Case only if each ElseIf statement in the If
construct evaluates the same expression

22
Programming constructs – Looping Structures
There are two options to choose from to repeatedly execute statements based on a condition

Do…Loop – These statements repeat execution of a block of For…Next – It uses a counter to increase/ decrease value of a
statements based on a condition. variable each time the loop is executed.
Syntax : Do While <condition> Syntax : For <counter> = <start> To <End> [Step Value]
<statements> <statements>
Loop Next [<counter>]

Example : Dim iCtr as Integer


Do While iCtr < 3
Msgbox “Ctr Value:” & iCtr Example : Dim iCtr as Integer
For iCtr = 1 to 3
iCtr = iCtr + 1
Msgbox “Ctr Value:” & iCtr
Loop
Next iCtr
Syntax : Do OR
<statements> Dim iCtr as Integer
Loop While <condition> For iCtr = 3 to 1 Step -1
Example : Msgbox “Ctr Value:” & iCtr
Dim iCtr as Integer
Next iCtr
iCtr = 4
Do
Msgbox “Ctr Value:” & iCtr The Exit statement can be used to break the execution of a
looping construct.
iCtr = iCtr + 1
Syntax: Exit <Do>/<For>
Loop While iCtr < 3
Example: Exit Do OR Exit For
23
Contents

1 Programming constructs in VBA

Functions & Procedures in VBA – Modularizing your


2 programs

3 Objects & Memory Management in VBA

4 Controlling accessibility of your code – Access specifiers

Code Reusability – Adding references and components to your


5 code
Functions & Procedures – Modularizing your programs

What is a procedure?

A procedure is a set of one or more program statements that can be executed by referring to the procedure name.

Example: Your program requires opening an Excel file several times through its execution. You can create a procedure that handles tasks
such as showing the user the Open Dialog Box to locate the file and then ask the user if the file is to be opened as read-only or not and then
actually open the file.
Hence, every time you want to open a file, all you need to do is call this procedure.

Advantages of using procedures : They help in making your code modular.


Code is easier to debug.
Code in a procedure is re-usable.

25
Functions & Procedures – Modularizing your programs

Types of Procedures

Procedures in VBA

Sub Procedures Property Procedures Function Procedures


A Function procedure is just like a
sub procedure except that a
General Procedures Event Procedures function procedure can return a
General procedures are blocks of code Event procedures are blocks of code that are value.
that perform a single task. They can executed when a specific event occurs, like a
e.g. “Public Function fSqrt (iNum
perform any task that is required button is clicked or a cell’s value is changed.
as Integer) As Double”
repeatedly in an application.
e.g. “Private Sub CommandButton1_Click()”
e.g. a procedure to open a file or for handles the click event for CommandButton1
connecting to a database

#
Property procedures are beyond the scope of this training.

26
Functions & Procedures – Modularizing your programs

Procedures and Functions – Syntax & Examples

Syntax Examples

General procedures
[Public | Private] Sub <procedureName> ([arguments]) Public Sub openFile (fileName as String)
[Statements] Dim xlApp As New Excel.Application
End Sub xlApp.Workbooks.Open(fileName)
End Sub

Event procedures
Private Sub <ObjName_EventName> ([arguments]) Private Sub CommandButton1_Click()
[Statements] Msgbox “You clicked on command button 1”
End Sub End Sub

Function procedures
[Public | Private] Function <procedureName> ([arguments]) As <Return Type> Public Function fSqrt (iNum as Integer) As Double
[Statements] fSqrt = sqrt(iNum)
End Function End Function

27
Contents

1 Programming constructs in VBA

2 Functions & Procedures in VBA – Modularizing your programs

3 Objects & Memory Management in VBA

4 Controlling accessibility of your code – Access specifiers

Code Reusability – Adding references and components to your


5 code
Objects & Memory Management
The NEW and SET Keywords

Syntax : [Dim | Public | Private] <objectName> As New <ObjectType>

Example : Dim xlApp As New Excel.Application

The New keyword, when used, accomplishes two tasks at a time - Object is declared & it is allocated memory as well.
In the above example, we have created a new Excel application object i.e. we executed a fresh copy of Excel.exe

The task illustrated above can also be done in two steps i.e. first declare the object and then allocate memory. This is accomplished
through the Set keyword.

Syntax : Set <objectName> = <FunctionName>

Example : Dim xlWkb As Excel.Workbook


Set xlWkb = Application.Workbooks.open (“C:\abc.xls”)

29
Objects & Memory Management
How to destroy an object – Release the memory held by it

The VBA constant Nothing can be used to destroy objects and release memory when no longer needed.

Syntax : Set <objectName> = Nothing

Example : Set xlApp = Nothing

30
Contents

1 Programming constructs in VBA

2 Functions & Procedures in VBA – Modularizing your programs

3 Objects & Memory Management in VBA

4 Controlling accessibility of your code – Access specifiers

Code Reusability – Adding references and components to your


5 code
Controlling accessibility of your code – Access specifiers

Where to write your code? *

Every Excel file is a VBA project in itself. The project explorer in the VBA IDE lists all the components/modules in the project.

VBA code in an Excel file can be placed in the following code modules :

 Sheet Modules – are special modules tied directly to each Sheet object. These
modules should contain the event procedures for the object.
 General Module – Your basic macros & your custom function (User Defined
Functions) should be in these modules. It is a module that is general-purpose and
not pertaining to anything graphic on-screen. Sheet
 User Form – A graphical user interface, different than the worksheets in an Excel modules
file. Part of the UserForm object & contain the event procedures for the controls on Workbook Module
that form.
 ThisWorkbook – A special module tied directly to the workbook object.

General Module User Form

* Types of Modules illustrated with MS Excel. Does not entirely apply to MS Access.
Code Modules in Excel – Further reading : http://www.cpearson.com/excel/codemods.htm

32
Controlling accessibility of your code – Access specifiers

How do you control your code’s availability?

The keywords Public & Private control what code & components are
available at what locations in the project. They work for all types of procedures, variables and constants.

Public : The procedure/component is available throughout the VBA project

Private : The procedure/component is available to all procedures within the module.


The Dim Keyword : A variable declared using the Dim keyword within a subroutine or function can only be accessed in the
procedure in which they’ve been declared.

33
Contents

1 Programming constructs in VBA

2 Functions & Procedures in VBA – Modularizing your programs

3 Objects & Memory Management in VBA

4 Controlling accessibility of your code – Access specifiers

Code Reusability – Adding references and components to


5 your code
Code Reusability – Adding references and components to
your code
What are Components?

A reference is a file available on your PC that has some pre-compiled set of code/controls that you can use in your tool/application.
References provide you the ability to add a lot of functionality/capabilities to your application by re-using code written by someone else.

These files are typically part of the MS Office package and can have any of the following file extensions : .dll, .exe or .ocx

What are References?

VBA comes packed with a lot of built-in components (*.ocx) that can be used to build user interfaces for our applications.

Most common examples include Buttons, check boxes, option buttons, text boxes, scroll bars, labels etc.
When working in Excel, we can add these controls on any of our sheets as well as on User Forms.
Code Reusability – Adding references and components to
your code
How to add a reference?

References can only be added through the VB IDE. The process to be followed is :

Tools Menu  References :


The list of references being used in a The references window :
VBA project are stored in the file and
are carried along.
Existing references
Any missing references or mismatch in
versions may throw runtime errors in
your code. Other available references

Location of the Reference


file
Code Reusability – Form controls and ActiveX controls

Excel provides us with two sets of User Controls that can be used on Excel sheets. Namely : ActiveX controls & Form (Excel) controls

Form Controls ActiveX Controls

These are available through the These are available through the
Forms toolbar in Excel Control Toolbox in Excel

These are legacy user controls that were introduced in ver 5 ActiveX controls are user controls that were part of VB and
of Ms Office. These controls are embedded within Excel and were embedded in Excel when VBA was integrated with Ms
are very light weight. Office. They are just like references that you add to your
project as each of these controls has a set of pre-compiled
Form controls are limited in number and provide very few
code behind it.
events and properties for manipulation.
These controls provide a large number of properties and
Form controls primarily are provided for backward
events for manipulation.
compatibility however, these are the only controls that can be
used on chart sheets. ActiveX controls exist as .ocx files.

37
Let’s look at our practice exercises and case study for this
session
Key Objectives for the Exercises + Case Study

Practice key control structures in VBA

Learn how to work with multiple Excel files

Learn how to think about and add validations in your code

Learn how to create your code in a dynamic way such that it can be updated and re-used easily

38
Type of Buttons
Return Values
1 OK vbOk
2 Cancel vbCancel 0 vbOKOnly OK button only
3 Abort vbAbort
4 Retry vbRetry
5 Ignore vbIgnore 1 vbOKCancel OK and Cancel buttons
6 Yes vbYes
7 No vbNo
vbAbortRetryI
2 Abort, Retry, and Ignore buttons
gnore

3 vbYesNoCance Yes, No, and Cancel buttons


l
4 vbYesNo Yes and No buttons

5 vbRetryCancel Retry and Cancel buttons

You might also like