AnalytixLabs - Training Module - Intro To Macros Programming
AnalytixLabs - Training Module - Intro To Macros Programming
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
It helps to understand that all programming languages are artificial languages and hence imitate human languages in several ways.
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.
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.
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 :
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 :
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.
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
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
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
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 :
...
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
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
16
Contents
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
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.
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>]
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.
25
Functions & Procedures – Modularizing your programs
Types of Procedures
Procedures in VBA
#
Property procedures are beyond the scope of this training.
26
Functions & Procedures – Modularizing your programs
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
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.
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.
30
Contents
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.
* 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
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.
33
Contents
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
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 :
Excel provides us with two sets of User Controls that can be used on Excel sheets. Namely : ActiveX controls & Form (Excel) 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
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