Excel VBA Intro
Excel VBA Intro
MS Excel VBA
Manual
Table of Contents
INTRODUCTION ................................................................................................................... 1
VISUAL BASIC EDITOR .......................................................................................................... 2
VISUAL BASIC FOR APPLICATIONS (50 MINS)................................................................. 2
THE PROJECT EXPLORER ........................................................................................... 4
THE PROPERTIES WINDOW ....................................................................................... 4
THE CODE WINDOW ................................................................................................ 4
OBJECT PROGRAMMING ....................................................................................................... 4
WHAT IS OBJECT PROGRAMMING?.............................................................................. 4
THE PROPERTIES WINDOW ....................................................................................... 4
MODIFYING PROPERTIES........................................................................................... 5
USING THE CODE WINDOW....................................................................................... 6
COLOURS IN THE CODE WINDOW ................................................................................ 7
USING METHODS .................................................................................................... 7
USING EVENTS........................................................................................................ 8
OBJECT-ORIENTATED PROGRAMMING OVERVIEW ........................................................... 9
THE OBJECT BROWSER ........................................................................................... 11
UNIT SUMMARY .................................................................................................... 12
PROGRAMMING BASICS ...................................................................................................... 14
DATA 14
DATA TYPES ......................................................................................................... 14
VARIABLES ........................................................................................................... 15
IMPLICIT DECLARATION .......................................................................................... 15
EXPLICIT DECLARATION........................................................................................... 16
CONSTANTS ......................................................................................................... 16
EXPRESSIONS ........................................................................................................ 17
OPERATORS ......................................................................................................... 17
THE CELLS OBJECT ................................................................................................. 17
FUNCTIONS .......................................................................................................... 18
USER INTERACTION FUNCTIONS ................................................................................ 18
CONCATENATING TEXT ........................................................................................... 19
OBJECT VARIABLES ................................................................................................ 20
-i -
SCOPE OF VARIABLES ............................................................................................. 21
DECLARATIONS SECTION ......................................................................................... 21
TYPES OF SCOPE .................................................................................................... 21
SCOPE OF PROCEDURES .......................................................................................... 22
PROCEDURE SCOPES ............................................................................................... 22
CALLING A SUB PROCEDURE ..................................................................................... 23
FUNCTION PROCEDURES ......................................................................................... 24
CALLING FUNCTION PROCEDURES.......................................................................................... 25
CALL A FUNCTION FROM CODE................................................................................. 25
CALL A FUNCTION USING INSERT FUNCTION DIALOG BOX ................................................ 25
CONTROL STRUCTURES ....................................................................................................... 28
DECISION STRUCTURES ........................................................................................... 28
IF...THEN...ELSE CONSTRUCTION ............................................................................. 28
IF THEN STATEMENT ............................................................................................... 30
IF THEN ELSE STATEMENT ........................................................................................ 31
IF THEN ELSEIF ELSE STATEMENT ............................................................................... 31
SELECT CASE STATEMENT ........................................................................................ 32
LOOP STRUCTURES ................................................................................................ 34
THE FOR… NEXT LOOP ........................................................................................... 34
THE FOR EACH… NEXT LOOP ................................................................................... 36
DO…LOOP STATEMENTS......................................................................................... 37
DO WHILE LOOP ................................................................................................... 37
CUSTOM DIALOG BOXES ..................................................................................................... 39
USER FORMS ........................................................................................................ 39
DESIGNING THE USER FORM.................................................................................... 39
NAMING OBJECTS .................................................................................................. 39
USER FORM INTERFACE .......................................................................................... 40
ADDING A USER FORM ........................................................................................... 40
USING CONTROLS .................................................................................................. 41
ADDING USER FORMS ............................................................................................. 42
EVENTS 45
EVENT HANDLING CODE .......................................................................................... 46
DATA VALIDATION ................................................................................................. 48
FORM CHECK LIST ................................................................................................. 49
Document1 "type section name here"
Page iii
COPY DATA TO ANOTHER WORK SHEET ..................................................................... 72
COPY DATA TO ANOTHER WORK BOOK...................................................................... 75
FILTERING DATA.................................................................................................... 78
FILTER THE FIRST FIELD OF THE TABLE/LIST FOR THE INPUTBOX VALUE .............................. 78
ACTIVECELL VALUE AS CRITERIA ................................................................................ 79
FILTER THE FIRST FIELD OF THE TABLE/LIST FOR THE TEXT VALUE OF RANGE("D1") ............. 80
IN THE EXAMPLE I FILTER ON THE FIRST COLUMN FOR THE NETHERLANDS .......................... 83
MACRO TO CLEAR THE FILTER IN THE TABLE/LIST ......................................................... 84
PRINT ODD AND EVEN PAGES ................................................................................... 86
INSERT PAGE BREAKS EVERY ? ROWS ......................................................................... 87
Document1 "type section name here"
Page v
Document1 SSSS
Introduction
All the Office 2010 applications allow users to create their own Visual Basic code to carry
out particular actions in the Application.
But why do you need to do this given that each application comes with a host of
powerful features? The answer lies in how these features are used.
VBA is present in Word 2010, Excel 2010, PowerPoint 2010, Outlook 2010, Project 2010
and Publisher 2010.
Access 2010 and Visio 2010 create VBA code a little differently and will be covered in
other Courses.
The purpose of this course is to give you the fundamental tools to start down the path of
VBA programming in Microsoft Excel and to encourage you to further your knowledge
beyond basic functionality; maybe you will use what you learn as the basis to explore
VBA in other applications.
Whatever path you decide to take the basic VBA for excel will give you the tools at your
fingertips to explore further.
Page 1
TTTT Excel VBA Introduction
VBA Terminology
Before you start coding in VBA you need to be familiar with some key terms associated
with it. The following table describes some of those terms.
Object VBA object is something like a tool or a thing that has certain functions
and properties, and can contain data. For example, an Excel Worksheet is
an object, cell in a worksheet is an object, range of cells is an object, font
of a cell is an object, a command button is an object, and a text box is an
object and more.
Property Each VBA object has its own properties that control its appearance. When
we talk about range as an object typical properties are:-
Column Width, Row Height, Font, Text, Value, Formula, Borders
Method While most objects only provide characteristics to describe them, other
objects can perform actions. For example, a house can be used to protect
people when it is raining outside. In computer programming, an action
that an object can perform is referred to as method.
Page 2
Document1 SSSS
Comment A line of text within a procedure, that you can use to describe each line of
code or the entire procedure. To comment a line out place an apostrophe
at the beginning of the line. The comment will turn green.
Module Is a file that you can write and edit blocks of code and other VBA code.
Project Explorer
Code Window
Properties Window
Page 3
TTTT Excel VBA Introduction
Object Programming
What is object programming?
In excel objects have certain properties, methods, and events. Properties control the
appearance and other attributes of an object. Methods are built in procedures that you
use to perform specific actions on an object. Events are actions such as mouse click
double click or open and close a workbook. Most objects in VBA have events associated
with them. For example a worksheet object has an event called activate.
Page 4
Document1 SSSS
Modifying Properties
EXERCISE 1
In the project explorer verify that sheet1 (sheet1) is selected
In the properties window double click name
Edit the value to read purchase sales 2012
Press the Enter Button
In the project explorer the worksheet name changes to purchase sales 2012
EXERCISE 2
in the properties window, double click standardwidth
enter 12
Select to view the changes
Point and Click between C & D a screen tip appears showing as 12
Page 5
TTTT Excel VBA Introduction
The code window contains two lists, the object list and the procedure list. The object list
displays all objects associated with the current module. The procedures list displays all
the procedures in the current module or all the events of the object selected in the
object list, the definition of the objects default procedure appears in the code window,
for example if you select the object worksheet from the object list the following code
appears in the window.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
End Sub
The code indicates that Worksheet_SelectionChangeis the defaultevent of the
worksheet object. This event occurs when the user selects a cell in the worksheet. Code
written within this procedure will execute every time this event occurs. For example if
you write code within this event procedure to display a specific message that message
will appear every time you select a different cell.
Type in the following to give it a try: MsgBox "you selected another cell"
The general syntax for changing object properties through code is
Object.property = Value
EXAMPLE
Sub change_name()
Worksheets("sheet1").Name = "myworksheet"
End Sub
Page 6
Document1 SSSS
Green Text prefixed with an apostrophe these are comments, and are
ignored when you run the code
Using Methods
Every object can perform certain actions are defined by methods. Some methods need a
value as input to complete their actions. For example, the open method of the
workbook object takes a file name as input so it knows specifically what workbook to
open. The input value is called an argument. An argument is a variable, constant or
expression that provides additional information to a method, so that it can execute
properly. To use a method in VBA code, you would use the following syntax.
Object.method argument1, argument2, argument3
For example to protect worksheet1 with the password “My Password”, you can use the
following code.
Sheet1.protect “mypassword”
EXERCISE 1
Add password protection to sheet 2 in a work book
Sub mypasson()
Sheet2.protect "mypassword"
End Sub
EXERCISE 2
Remove password protection to sheet 2 in a work book
Sub mypassoff()
Sheet2.Unprotect "mypassword"
End Sub
Page 7
TTTT Excel VBA Introduction
Using Events
You might want a procedure to run in response to a specific user action. You can do this
by associating the code with an event object. This association is created using an event
procedure.
An event procedure is a code that is executed when an event occurs. For example, you
can write code for the activate event of a worksheet to display a message indicating that
you cannot change the data in the worksheet this procedure will activate when the user
activates the worksheet.
To program an event, double click the object to display a code window. Select an event
from the procedure list and enter the code, the code will run automatically when a user
triggers the event for that procedure.
EXERCISE
Switch to the VBE Window
In the project explorer verify that sheet3 is selected
In the Code window, from the object list, select Worksheet (left)as shown above from
the procedures list select Activate (right)
Type the following:
Sheet3.protect “password”
MSGBOX (“protected Worksheet. You cannot edit the data in the list.”)
Switch to excel
Click on sheet3 to see the results
Page 8
Document1 SSSS
Object
Properties Events
Make On-start
Model On-Parked
Colour On-Brake
Year
Price
Methods
Start
Drive
Park
Page 9
TTTT Excel VBA Introduction
Using Buttons
The following procedure shows you how to add a button to the worksheet and assign
code to that button.
From the ribbon bar navigate to the developers tab, from the
controls group select insert then click on the button icon.
Draw the button to the size required.
Next the macros dialog box opens, in the macro name box
type in calculate, next click on new. Insert the code below in
the code window.
Sub Calculate()
ActiveCell.FormulaR1C1 = "=Product(rc[-2]:rc[-1])"
End Sub
The code when executed adds two numbers to the left of a highlighted cell. Later on we
will look at the looping stamen to automatically add up all values in the columns.
Page 10
Document1 SSSS
Project/Library list shows the names of all the projects and object library’s
Search Text Box, accepts text strings and searches for information related to the
text typed in.
Search results shows the results of the information typed into the search text box
Classes list shows the classes that are available depending on what has been
selected from the project library list.
Members of list, shows the methods and properties that belong to a particular
object.
Details Pane shows the definition and syntax of a selected method, property or
event.
Page 11
TTTT Excel VBA Introduction
Object / Class
Method
Event
Properties
Help Button
Search Button
Unit summary
In this unit you have learnt that VBA is a programming language been introduced to the
Visual basic Editor, Terminology use in VBA and gained an understanding of how objects,
properties, methods and events play a role in Object-orientated programming.
You have learnt how to modify properties and use methods by using the code window,
you also learned how to associate code to an event, and finally in this section you added
a button to execute some VBA code.
In the last part of this section we looked at how the object browser worked, familiarised
ourselves with the interface and icon sets and performed a search to find out
information about properties and methods.
Page 12
Document1 SSSS
Notes:
Page 13
TTTT Excel VBA Introduction
Programming Basics
Data
Programs receive data as input then process that data to generate output, a good
example of this is a calculator where you input numbers, instruct it which operator to
use and it then returns an output as the answer. When inputting data the program uses
a temporary storage space called a variable, the variable consists of a name and data
type. The name is used to identify itself in the program and the data type indicates the
type of data to be stored. In VBA it’s not mandatory to specify the data type if you don’t
it will assign a type called variant, however specifying data types makes the code run
more efficiently.
Data Types
Type Storage Range of Values
String(fixed Length of
1 to 65,400 characters
length) string
String(variable Length + 10
0 to 2 billion characters
length) bytes
Length+22
Variant(text) Same as variable-length string
bytes
Page 14
Document1 SSSS
Variables
We have established that variables are used in VBA to store data and the name given to
it uniquely identifies the variable in the computer memory. For example in a procedure
that calculates a commission value, you would create a variable to contain that value.
The process of defining a variable and its data type is called declaration; there are two
types of declaration in VBA either implicitly or explicitly.
Implicit Declaration
You can use a variable without declaring it. This is called implicit declaration, consider
the following code.
Answer = 100 + 100
In the code above we have a variable called Answer this holds the sum of the two
answers.
Page 15
TTTT Excel VBA Introduction
Explicit Declaration
As you have discovered implicit declarations are open to errors in the code, to prevent
errors and control the type of variable used we need to set an explicit Declaration. To
make sure this action takes place type Option Explicit at the top of the code window as
shown below. With your cursor inside the code press F5 to run the code as you can see
from the dialog box we get a compile error complaining the variable is not found.
To make this code run we have to declare the variables add the following code line to
the sub routine. Dim answer As Integer the code will now run to display the correct
result. You can declare more than one variable at a time, for example Employee
surname and salary amount as.
Dim Salary_ammount as Double, Employee_name as string
Constants
A constant is a special type of variable that holds static data Tax rates commission rates
and scientific constants are good uses for this variable to be used. To declare a constant
use following syntax const <constant_name> = Value, for example setting the current
vat rate as a constant may be written as Const VAT=0.20
Option Explicit
Const VAT = 0.2
Sub calc()
Dim answer As Integer
Answer = (100 + 100) * VAT
MsgBox (answer)
End Sub
Type in the code above this will result in 40 being displayed in the dialog box.
Page 16
Document1 SSSS
Expressions
An expression is a combination of operators, constants, procedures and names of
controls and properties that is evaluated to obtain a result. When you use an expression
in code it returns a value in one of the data types provided by VBA.
Operators
Operators are arithmetic symbols
Arithmetic Operators Comparison Operators
+ Addition < Less than
- Subtraction > Great than
/ Division = Equal to
* Multiplication <> Not equal to
A comparison operator returns a Boolean value because the result of any comparison is
always true or false
Page 17
TTTT Excel VBA Introduction
Functions
If you have got to the stage of learning VBA then you will be proficient already in excel
and would have used many of the inbuilt functions, functions always return results.
Page 18
Document1 SSSS
Concatenating text
You can use the message box function to display text along with the value stored in a
variable. To combine variables with text you can use the concatenation operator
ampersand (&). The general syntax for using the concatenation operator ampersand is:
Msgbox (“message_text” &<variable_name>
For example to display the message “the amount is”, along with the value that is stored
in the variable amount, the code is:
Msgbox (“the amount is:”& amount)
Sub join()
Dim Amount As Integer
Amount = InputBox("enter a value")
MsgBox "The Amount is:" & "£" & amount
End Sub
The code above takes the value you enter in an input box, then displays that as The
amount is £90 that is on the assumption you have typed 90 into the input box.
Try typing in the code below comment out each line to describe what it does.
Sub usingfunctions()
Dim saleseast As Integer, saleswest As Integer, sum As Integer
MsgBox "please enter whole numbers only"
saleseast = InputBox("enter the total sales for the east")
saleswest = InputBox("enter the total sales for the west")
sum = saleseast + saleswest
Cells(2, 4).Value = sum
MsgBox "total sales for east and West: £" & sum
End Sub
Page 19
TTTT Excel VBA Introduction
Object Variables
In another example of a variable we can define an object variable in the example shown
we are going to change the colour of the tab colour of two worksheets one to red and
one to green, using object variables is discussed in depth in a later course.
The code above sets variable WKS as a worksheet object, worksheets are a member of
the workbook family, and inside the parentheses we define the worksheet name. The
property of the tab is changed by referencing the object variable and setting the
property to the appropriate colour.
Page 20
Document1 SSSS
Scope of Variables
Having set up variables it may become apparent that you need to use it in more than
one procedure, rather than copy to each individual module we can broaden its scope or
put another way its usability. The accessibility or scope is determined where the variable
has been declared.
Declarations Section
The top of the code window includes a declaration section; variables placed here can be
used by all procedures within the module remember option explicit is also set in this
area.
Types of Scope
Three types of scope are available in VBA as already stated the scope of a variable is
determined by the way you declare it.
Procedure-level, when you declare a variable within a procedure it is not accessible
outside of the procedure. A procedure level variable is only available within the
procedure it is written.
Private module-Level, when declaring a variable in the declaration section of a module
using Dim or Private keyword the variable is known as a private module-level variable,
the variable can be used by any procedure within the module but cannot be accessed by
a procedure outside the module.
Public Module Level, when a variable is declared in the declaration section with the
prefix keyword public, the variable is called a public module-level variable these
variables can be called from any procedure or module.
Page 21
TTTT Excel VBA Introduction
Scope of Procedures
You may have a procedure that performs a general function like multiplying the value of
two numbers; this procedure can be included in different modules by giving it the
relevant scope. You can also specify a type for the procedure it can be one of the
following, Sub, function or property function procedure is similar to a sub function but
whereas the sub procedure executes code the function procedure returns a value.
Procedure scopes
The general syntax that determines the procedure scope is as follows
Private/Public sub <procedure name>()
<Procedure Body>
End Sub
Understanding the syntax
Public indicates that the procedure can be used in different modules.
Private indicates the procedure can only be used in the current Module.
Sub / End Sub the start and the end of the procedure.
<Procedure name>denotes the name of the procedure, you must give a unique name
and it must not be the same as any of the VBA Keywords.
<Procedure Body>, denotes the code for the procedure. A procedure can have one or
more statements that are executed sequentially.
Page 22
Document1 SSSS
This is the function that you run in turn it calls the information from
above, calculatesalestax takes the value and multiply it by .08 this
information is then stored in the variable ST. then the contents of cell D5
are added to the Result of ST
Page 23
TTTT Excel VBA Introduction
Function procedures
Similar to sub procedures in the way that are written but a function returns a value. The
value that the function produces is stored in a predefined variable. The scope of the
function will be either private or public.
Remember you can also add a function through the add procedure dialog
box, you make your selections and the correct deceleration is added to the
module when you click ok
Page 24
Document1 SSSS
Page 25
TTTT Excel VBA Introduction
This launches the insert dialog box on the or select a category drop down box select
user defined as shown below, in the select function pane you should see MPG select
and click ok.
Next the input function arguments dialog box for MPG opens enter the cell references
for start_miles, end_miles and fuel_used as shown below, click OK to complete.
Page 26
Document1 SSSS
Notes:
Page 27
TTTT Excel VBA Introduction
Control Structures
Decision Structures
Decision structures allow the program to execute various procedures dependant on an
outcome if a condition is met run one procedure if not run an alternative procedure, it is
possible to run nested decision structures within VBA using the correct syntax.
If...Then...Else Construction
If...Then...Else constructions allow you to test for one or more conditions and run one or
more statements depending on each condition. You can test conditions and take actions
in the following ways:
The control structure that offers all these possibilities is the If...Then...Else Statement in
(VBA). You can use a single-line version if you have just one test and one statement to
run. If you have a more complex set of conditions and actions, you can use the multiple-
line version.
Sub test ()
If condition [Then]
[statements]
[ElseIf elseifcondition [Then ]
[ elseifstatements ] ]
[ Else
[ elsestatements ] ]
End If
-or-
If condition Then [ statements ] [ Else [ elsestatements ] ]
End sub
Page 28
Document1 SSSS
Syntax property
Condition
Required. Expression. Must evaluate to True or False, or to a data type that is
implicitly convertible to Boolean.
Then
Required in the single-line form, optional in the multiple-line form.
Statements
Optional. One or more statements following If...Then that are executed if condition
evaluates to True.
Elseifcondition
Required if ElseIf is present. Expression. Must evaluate to True or False, or to a
data type that is implicitly convertible to Boolean.
Elseifstatements
Optional. One or more statements following ElseIf...Then that are executed if
elseifcondition evaluates to True.
Elsestatements
Optional. One or more statements that are executed if no previous condition or
elseifcondition expression evaluates to True.
End If
Terminates the If...Then...Else block.
Page 29
TTTT Excel VBA Introduction
If then statement
In this procedure we check a cell reference to check to see if the vale is greater than 100
if the cell evaluates greater than 100 the function is deemed as true and places the
message “very high mpg” in cell E4 at the end if it breaks out and continues to run the
remainder of the procedure, in this case places a value in cell G4
Example 1
Sub test1()
If Cells (4, 5).Value > 100 then
Cells (4, 6).Value = "Very high MPG"
End If
Cells (4, 7).Value = 200
End Sub
In this procedure two variables have been set score and grade score is = to value of cell
A1, when run this procedure checks the value of cell A1 if the value is greater than the
result is passed. Otherwise the cell stays empty
Example 2
Sub test2()
Dim score As Integer, grade As String
score = Range("A1").Value
If score >= 60 Then grade = "passed"
Range("B1").Value = grade
End Sub
Page 30
Document1 SSSS
Page 31
TTTT Excel VBA Introduction
Page 32
Document1 SSSS
Substitute case is>with case 400 to 500 this checks if a value is between
two values
Page 33
TTTT Excel VBA Introduction
Loop Structures
You use loop structures such as for… next and for each …next when you want to run a
specific block of text repeatedly. Use one of two loop structures depending on the
number of iterations that are required.
Fixed iterationThis runs a set of statements for a predetermined number of
times.Example For… next loop
Indefinite Iterationthis runs a set of statement until a defined condition is met.
Example Do …while loop
Example 1
Sub count()
Dim count As Integer
For count = 1 To 3
'this adds 1+2+3
Sum = Sum + count
Next count
'places answer in a cell
Cells(2, 2).Value = "the sum of the amount counts " & Sum
'you could use this if the value added to a worksheet is not visible to the user
MsgBox ("the sum of the amount counts " & Sum)
End Sub
Page 34
Document1 SSSS
Example 2
Next we consider a nested if function and how we can convert it into code.
=IF(A1<500,A1*0,IF(A1<=1000,A1*10%,A1*30%))
Sub count2()
Dim count As Integer
For count = 1 To 20
totalsales = Cells(count, 1).Value
If totalsales >= 500 Then
commisionamnt = totalsales * 0.1
ElseIf totalsales > 1000 Then
commisionamnt = totalsales * 0.3
Else
commisionamnt = totalsales * 0
End If
Cells(count, 2).Value = commisionamnt
Next count
End Sub
Page 35
TTTT Excel VBA Introduction
Example 1
In this example we set a variable as cell setting it to range
Sub ShowValue()
Dim cell As Range
For Each cell In Selection
MsgBox cell.Value
Next
End Sub
Example 2
In this exercise if a cell has a number in the range A1:A50 the procedure will Double the
cell value, if it contains a number,otherwise clear the cell.
Sub ForEachCollectionLoop2()
For Each cell In Range("A1:G50")
If IsNumeric(cell) Then
cell.Value = cell.Value * 2
Else
cell.Clear
End If
Next
End Sub
Page 36
Document1 SSSS
Do…Loop Statements
Do While Loop
When a process has to be repeated it is best to use a loop structure to make sections
ofinstructions repeat rather than have multiple sets of duplicated instructions.
Now we introduce you to Conditional LoopsRepetition while a certain condition is
satisfied or until a certain condition is satisfied.
Check for the condition before running the loop:
Do Whilecondition
Statements
Loop
Execute the commands once before checking the condition:
Do
Statements
Loop Whilecondition
Use the keywords Until or While to define the condition, placing them either at the
top orat the end of the Do…Loop.
Example 1
X=10 and is our base number DO Until X is greater than 40 Adds 10 to the base
SubDoLoops1()
x = 10
Do Untilx > 40
x = x + 10
MsgBox x
Loop
End Sub
Example 2
Sub DoLoops2()
x = 10
Do
x = x + 10
MsgBox x
Loop While x < 40
End Sub
Page 37
TTTT Excel VBA Introduction
Page 38
Document1 SSSS
Naming objects
It is awkward having to use the default object names when you are completing the event
procedures for each control; is the OK button CommandButton1 or is it
CommandButton2? Follow the published standard conventions for Control names, add
the three-character lower case prefix to your names and you will never have any
problems identifying your control objects in code.
Ob
Check Box chk
Combo Box cbo
Command Button cmd
Frame Fra
Label lbl
List Box Lst
Option Button opt
Text Box txt
Toggle Button Tog
User Form frm
Prefix
Page 39
TTTT Excel VBA Introduction
Page 40
Document1 SSSS
Using Controls
Page 41
TTTT Excel VBA Introduction
In the example above you will create a user form to enter the employee name, their
Department from a list enter their earnings and add two controls one to enter the data
and one to close the form.
Switch from the excel view to the visual basic editor, from the insert menu select user
form. The screen will now look as shown below. If the toolbox is not displayed from the
menu bar select view toolbox.
Click the and draw the label box as shown resize the label as shown below
Page 42
Document1 SSSS
Before we go any further click on the form navigate to the form property’s box in name
type Employeeinfo
Change the properties of the name to read txtempnamenow add a further label below
employee name, change the properties in caption to Department.
Now we are going to add a List Box click on the icon add the list box below
employee name input box. To show as below.
Page 43
TTTT Excel VBA Introduction
Two more buttons to add these are to be command buttons lay out as shown below.
Now we shall finish it off navigate to the properties of the form in the caption box type
the following. Employee Information now for the commandButton1 in the properties
change the caption to Enter Data change the name property to CmdAdd
now for the commandButton2 in the properties change the caption to Close change the
name property to CmdClose your form should now look like the one below.
We have now created our user form click the save button to update and save your work
In the next section we will look at events and how to transfer data from the user form to
the excel data sheet.
Page 44
Document1 SSSS
Events
VBA is based around event – driven programming. In other words the code doesn’t
follow a predetermined path, instead it responds to events that a user or condition that
occurs. For example the click of a button generates an event, the on_click event.
Procedures are executed when an event is triggered. User forms and their controls
respond to the events that are associated with them. Below is a list of events and their
triggers.
Page 45
TTTT Excel VBA Introduction
Double click on the command button EnterData the code window opens as below
End Sub
Add the following code to read as below this stores the data from the form to the spread
sheet in the following Cells A12 ,B12, C12
End Sub
Double click on the command button Close the code window opens as below
Employeinfo.Hide
End Sub
Now switch to the excel spread sheet and add a control button from the developers tab
controls group, insert drop down, button form_control.
Draw the button and the assign macros button dialog box opens, click on New
Enter the code as shown below, Edit the text on the Button face to say OPEN
Sub Button1_Click()
Employeinfo.Show
End Sub
Page 46
Document1 SSSS
Marketing
HR
IT Support
It Helpdesk
Banking
Sales
Finance
Having clicked on the open user form button the employee information form will open
Enter the details you wish to add to the spread sheet, click enter data to transfer the
contents of the form to the spread sheet, click close to exit the form.
Page 47
TTTT Excel VBA Introduction
Data Validation
If a user accidently enters the wrong data or data is missing we want to be able to set in
place some rules of checking that information, this is known as validation.
Navigate to the VBA Editor window
On the textempearnings enter the following code
nextrow = Application.WorksheetFunction.CountA(Range("a:a")) + 1
Page 48
Document1 SSSS
Page 49
TTTT Excel VBA Introduction
Error Types
There are three types of programming error, compile time, run time and logical. The
following table describes the type of error.
Error Description
Compile-error A compile-time error happens when the
program is being compiled. Generally,
compile-time errors are syntax errors; and
they are caught by the compiler.
Page 50
Document1 SSSS
Error Types
Compile Time error
Compile Time error This is because no Endif Present
Sub calculationbonus()
Dim bonus As Currency, earnings As Currency
earnings = InputBox("enter earnings")
If earnings > 40000 Then
bonus = earnings * (12 / 100)
MsgBox "the bonus is " & bonus
End Sub
Logical Error
This is a logical error the + has been used instead of the*
Sub bonus()
Dim bonusamt As Currency, salesamt As Currency
salesamt = 10
bonusamt = salesamt + (6 / 100)
MsgBox "bonus is " & bonusamt
End Sub
Sub bonus()
Dim bonusamt As Currency, salesamt As Currency
salesamt = 10
bonusamt = salesamt * (6 / 0)
MsgBox "bonus is " & bonusamt
End Sub
Page 51
TTTT Excel VBA Introduction
Debugging
To create an error free application you need to be able to trace an correct errors when
they occur, the process is called debugging. VBA provides the following tools to help you
debug your code these are located on the debug toolbar.
Debugging tools
The following table describes the tools available to you in VBA to view values of
variables and expressions and trace the execution of a program.
Tool Used To
Break Point Pause the execution of code at a specified statement.
You can insert a breakpoint in the first line of code
segment that you suspect to be the cause of the error.
You can then monitor the execution of the code
Watch Window Monitor values of specified variables and expressions
while the code is running
Immediate Window Test your output by assigning different values to
variables or expressions
Locals Window Monitor all the declared variables of the procedure
currently running
Page 52
Document1 SSSS
Setting a Breakpoint
Open a new work book and layout the data as shown below
Save as my debugging tools
Option Explicit
Dim TotalSales As Currency, CommissionAmt As Currency
Page 53
TTTT Excel VBA Introduction
Page 54
Document1 SSSS
Watch Expressions
Some errors may not be traceable to a single statement in your code, for example in
some logical errors it’s difficult to isolate the line of code that is causing the error. In
cases such as this you need to monitor the behaviour the expressions and variables of
the entire procedure. Each expression or variable you monitor is known as a watch,
watch expressions can be defined in either break mode or design time.
VBA automatically monitors and displays the expressions in the watch window.
The watch window is displayed automatically when you enter break mode or you choose
to open the watch window manually by clicking the watch window button on the debug
toolbar. The watch window can be used to change values of variables and expressions
this allows you to observe how these changes to affect the code.
Consider the following, using the file you have already created make sure you are
in the VBE window
Select debug then add watch
In the expression box type totalsales, the variable to watch, in the context region
make sure the procedure list refers to commision and the module list states sheet1
then set watch type to watch expression
Click ok
Repeat the procedure this time add CommissionAmt
Update the code
Now these watches are in place we shall now use stepping through code in the next
section to see how they work.
Page 55
TTTT Excel VBA Introduction
Step into, runs each executable line of code sequentially and steps into the
procedure. This allows you to observe the effect of each statement on variables. To
step into the code either choose debug step into or press F8 or click step into
button on the debug toolbar.
Step Over, this runs each procedure as if it was a single statement, you can use this
to skip calls to other procedures from the current procedure. To step over code
choose debug, step over, click step over button on the debug toolbar or press shift
+ F8.
Step Out, runs the remaining code in the current procedure as a single statement.
If the current procedure is a called procedure the remaining code in the procedure
is executed and the debugging stops at the next statement in the calling procedure.
To step out of the code, choose debug, step out. You can also click Ctrl+Shift+F8 or
click step out button on the debug toolbar.
Now we understand what stepping through procedure and how it works we shall now
put that into practice.
Page 56
Document1 SSSS
Page 57
TTTT Excel VBA Introduction
With the employee information work book open make sure you are on the
employeeinfo worksheet.
Switch to the VBE window
Make sure the employeeinfo code window is selected
Page 58
Document1 SSSS
Option Explicit
Dim Percentage As Single
Dim Earnings As Currency, TotalEarnings As Currency, Bonus As Currency
Public Sub NetEarnings()
Percentage = 6
Earnings = Cells(4, 6).Value
Bonus = Earnings * (Percentage / 100)
TotalEarnings = Earnings + Bonus
Cells(4, 7) = TotalEarnings
End Sub
Point your cursor art the first procedure as shown note the variable
percentage as 6
Press F8 to run the line that calculates the bonus amount and move to the next line
In immediate window type Print Bonus to view the bonus amount in the
immediate window
Press the Enter Key to display the bonus amount.
On the next line of the immediate window type percentage = 20
Press the Enter Key
Page 59
TTTT Excel VBA Introduction
Locals Window
The locals window helps you monitor the values of variables within the current
executing procedure or function
The Locals Window
VBA provides one way to access the objects from which Excel is composed. Start to
examine these objects by writing a short routine to change the value of a variable.
Activate the VB Editor, select Insert/Module and enter the following subroutine in the
code window:
Sub SampleVariable()
Dim aval As Variant
aval = 200
aval = 123.123
aval = "Cat"
aval = True
aval = #12/1/1998#
End Sub
Now select the Locals Window command from the View menu and then use the F8 key
to step through the subroutine.
You will see the entries in the Locals Window change as each line is executed with the
contents and type of each variable displayed in turn.
Page 60
Document1 SSSS
Error-handling
Error handling refers to the programming practice of anticipating and coding for error
conditions that may arise when your program runs. Errors in general come in three
types:
compiler errors such as undeclared variables that prevent your code from compiling;
user data entry error such as a user entering a negative value where only a positive
number is acceptable;
Run time errors, that occur when VBA cannot correctly execute a program statement.
We will concern ourselves here only with run time errors. Typical run time errors
include attempting to access a non-existent worksheet or workbook, or attempting to
divide by zero. The example code in this article will use the division by zero error (Error
11) when we want to deliberately raise an error.
If you have no error handling code and a run time error occurs, VBA will display its
standard run time error dialog box. While this may be acceptable, even desirable, in a
development environment, it is not acceptable in a production environment.
The goal of well-designed error handling code is to anticipate potential errors, and
correct them at run time or to terminate code execution in a controlled, graceful
method. Your goal should be to prevent unhandled errors from arising.
Page 61
TTTT Excel VBA Introduction
appropriate action. You do this by testing the value of Err.Number and if it is not zero
execute appropriate code. For example,
On Error Resume Next
N = 1 / 0 ' cause an error
If Err.Number <> 0 Then
N=1
End If
This code attempts to assign the value 1 / 0 to the variable N. This is an illegal
operations, so VBA will raise an error 11 -- Division By Zero -- and because we have On
Error Resume Next in effect, code continues to the If statement. This statement tests the
value of Err.Number and assigns some other number to N.
Page 62
Document1 SSSS
When the first error is raised, execution transfers to the line following Err1:. The error
hander is still active when the second error occurs, and therefore the second error is not
trapped by the On Error statement.
Used alone, Resume causes execution to resume at the line of code that caused the
error. In this case you must ensure that your error handling block fixed the problem that
caused the initial error. Otherwise, your code will enter an endless loop, jumping
between the line of code that caused the error and the error handling block.
The following code attempts to activate a worksheet that does not exist. This causes an
error (9 - Subscript Out Of Range), and the code jumps to the error handling block which
creates the sheet, correcting the problem, and resumes execution at the line of code
that caused the error.
ErrHandler:
If Err.Number = 9 Then
' sheet does not exist, so create it
Worksheets.Add.Name = "NewSheet"
' go back to the line of code that caused the problem
Resume
End If
Page 63
TTTT Excel VBA Introduction
The second form of Resume is Resume Next . This causes code execution to resume at
the line immediately following the line which caused the error. The following code
causes an error (11 - Division By Zero) when attempting to set the value of N. The error
handling block assigns 1 to the variable N, and then causes execution to resume at the
statement after the statement that caused the error.
ErrHandler:
N=1
' go back to the line following the error
Resume Next
The third form of Resume is Resume <label>: . This causes code execution to resume at
a line label. This allows you to skip a section of code if an error occurs. For example,
ErrHandler:
' go back to the line at Label1:
Resume Label1:
Page 64
Document1 SSSS
A Note Of Caution
It is tempting to deal with errors by placing an On Error Resume Next statement at the
top of the procedure in order to get the code to run without raising an error. This is very
bad coding practice. Remember that using On Error Resume Next does not fix errors. It
merely ignores them.
Page 65
TTTT Excel VBA Introduction
[A1] Cell A1
Page 66
Document1 SSSS
Square brackets
The full object reference to the worksheet cell A1 is Range("A1"). If you are typing-in cell
references rather than recording, it is easier to use the shortcut notation using square
brackets, [A1]. You can use the same style of referencing on other objects as well, such
as worksheets but there are a number of rules and restrictions.
It is usually best to restrict the square bracket notation to cell references only, where it
is entirely definitive and reliable.
With…End With
The With statement is used so the object reference can be made and then retained so
that multiple actions may be carried out without having to repeat the same object
reference in each statement.
You can keep the With reference open for as long as you like in the same procedure, just
pointing to it using the dot operator. Every With requires an End With. You can have
Page 67
TTTT Excel VBA Introduction
multiple With pointers. When you are reading code that uses multiple With pointers, the
rule is simple; the dot points to the nearest With.
With Object
.Property
With .Child Object
.Method
.Method
End With
End With
Page 68
Document1 SSSS
Sub GoToManual()
Dim xlCalc As XlCalculation
xlCalc = Application.Calculation
Application.Calculation = xlCalculationManual
On Error GoTo CalcBack
'YOUR CODE
Application.Calculation = xlCalc
Exit Sub
‘CalcBack:
Application.Calculation = xlCalc
End Sub
Sub NoScreenRePainting()
Application.ScreenUpdating=False
'Your code here.
Application.ScreenUpdating=True
End Sub
Page 69
TTTT Excel VBA Introduction
Sub NoAutoFillOrCopy()
Range("A1:A200").FormulaR1C1 = "=SUM(RC[1]:RC[5])"
End Sub
Page 70
Document1 SSSS
Page 71
TTTT Excel VBA Introduction
Page 72
Document1 SSSS
End With
On Error GoTo 0
If CCount = 0 Then
MsgBox "There are more than 8192 areas, so it is not possible to " & _
"copy the visible data to a new worksheet. Tip: Sort your " & _
"data before you apply the filter and try this macro again.", _
vbOKOnly, "Copy to new worksheet"
Else
'Copy the visible cells.
ACell.ListObject.Range.Copy
'Add a new Worksheet
Set New_Ws = Worksheets.Add(after:=Sheets(ActiveSheet.Index))
'Ask for the Worksheet name
sheetName = InputBox("What is the name of the new worksheet?", _
"Name the New Sheet")
On Error Resume Next
New_Ws.Name = sheetName
If Err.Number > 0 Then
MsgBox "Change the name of sheet : " & New_Ws.Name & _
" manually after the macro is ready. The sheet name" & _
" you fill in already exists or you use characters" & _
" that are not allowed in a sheet name."
Err.Clear
End If
On Error GoTo 0
'Paste the data in the new worksheet
With New_Ws.Range("A1")
.PasteSpecial xlPasteColumnWidths
.PasteSpecial xlPasteValuesAndNumberFormats
.Select
Application.CutCopyMode = False
End With
'Call the Create List or Table dialog.
Application.ScreenUpdating = True
Page 73
TTTT Excel VBA Introduction
Application.CommandBars.FindControl(ID:=7193).Execute
New_Ws.Range("A1").Select
ActiveCellInTable = False
On Error Resume Next
ActiveCellInTable = (New_Ws.Range("A1").ListObject.Name <> "")
On Error GoTo 0
Application.ScreenUpdating = False
'If you not want to create a table it will run the code below
If ActiveCellInTable = False Then
Application.GoTo ACell
CopyFormats = MsgBox("Do you also want to copy the Formats ?", _
vbOKCancel + vbExclamation, "Copy to new worksheet")
If CopyFormats = vbOK Then
ACell.ListObject.Range.Copy
With New_Ws.Range("A1")
.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End With
End If
End If
End If
'Select the new worksheet if not active
Application.GoTo New_Ws.Range("A1")
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
Else
MsgBox "Select a cell in your List or Table before you run the macro", _
vbOKOnly, "Copy to new worksheet"
End If
End Sub
Page 74
Document1 SSSS
Page 75
TTTT Excel VBA Introduction
'Test if there are more than 8192 separate areas. Excel only supports
'a maximum of 8,192 non-contiguous cells through VBA macros and manual.
If CCount = 0 Then
MsgBox "There are more than 8192 areas, so it is not possible to " & _
"copy the visible data to a new workbook. Tip: Sort your " & _
"data before you apply the filter and try this macro again.", _
vbOKOnly, "Copy to new workbook"
Else
'Copy the visible cells to the new workbook
ACell.ListObject.Range.Copy
'Add a new workbook with one worksheet
Set New_Ws = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
'Paste the data in the worksheet in the new workbook
On Error Resume Next
With New_Ws.Range("A1")
.PasteSpecial xlPasteColumnWidths
.PasteSpecial xlPasteValuesAndNumberFormats
.Select
Application.CutCopyMode = False
End With
On Error GoTo 0
'Call the Create List or Table dialog
Application.ScreenUpdating = True
Application.CommandBars.FindControl(ID:=7193).Execute
New_Ws.Range("A1").Select
ActiveCellInTable = False
On Error Resume Next
ActiveCellInTable = (New_Ws.Range("A1").ListObject.Name <> "")
On Error GoTo 0
Application.ScreenUpdating = False
'If you not want to create a Table it will run the code below
If ActiveCellInTable = False Then
Application.GoTo ACell
Page 76
Document1 SSSS
End If
'Select the new workbook if not active.
Application.GoTo New_Ws.Range("A1")
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
Else
MsgBox "Select a cell in your List or Table before you run the macro", _
vbOKOnly, "Copy to new workbook"
End If
End Sub
Page 77
TTTT Excel VBA Introduction
Filtering Data
Option Explicit
'There are four filter examples in this module
'And a macro example to clear the filter below the filter examples
'1: Filter on InputBox value
'2: Filter on ActiveCell value
'3: Filter on Range value (D1 in this example)
'4: Criteria in the code (Netherlands, with tips below the macro)
Filter the first field of the Table/List for the inputbox value
Sub FilterListOrTableData()
'Works in Excel 2003 and Excel 2007.
Dim ACell As Range
Dim ActiveCellInTable As Boolean
Dim FilterCriteria As String
'Use this line if you want to select a cell in the Table with code.
'Application.GoTo Sheets("Yoursheetname").Range("A24")
If ActiveSheet.ProtectContents = True Then
MsgBox "This macro is not working when the worksheet is protected", _
vbOKOnly, "Filter example"
Exit Sub
End If
'Set a reference to the ActiveCell named ACell. You can always use
'ACell now to point to this cell, no matter where you are in the workbook.
Set ACell = ActiveCell
'Test to see if ACell is in a table or list. Note that by using ACell.ListObject, you
'don't need to know the name of the table to work with it.
On Error Resume Next
ActiveCellInTable = (ACell.ListObject.Name <> "")
On Error GoTo 0
'If the cell is in a list or table, run the code.
If ActiveCellInTable = True Then
Page 78
Document1 SSSS
End Sub
Sub FilterListOrTableData2()
'Works in Excel 2003 and Excel 2007.
Dim ACell As Range
Dim ActiveCellInTable As Boolean
Dim FilterCriteria As String
'Use this line if you want to select a cell in the Table with code.
'Application.GoTo Sheets("Yoursheetname").Range("A24")
If ActiveSheet.ProtectContents = True Then
MsgBox "This macro is not working when the worksheet is protected", _
vbOKOnly, "Filter example"
Exit Sub
End If
Page 79
TTTT Excel VBA Introduction
'Set a reference to the ActiveCell named ACell. You can always use
'ACell now to point to this cell, no matter where you are in the workbook.
Set ACell = ActiveCell
'Test to see if ACell is in a table or list. Note that by using ACell.ListObject, you
'don't need to know the name of the table to work with it.
On Error Resume Next
ActiveCellInTable = (ACell.ListObject.Name <> "")
On Error GoTo 0
'If the cell is in a list or table, run the code.
If ActiveCellInTable = True Then
'Show all data in the table or list.
On Error Resume Next
ActiveSheet.ShowAllData
On Error GoTo 0
'This example filter on the ActiveCell value
ACell.ListObject.Range.AutoFilter _
Field:=ACell.Column - ACell.ListObject.Range.Cells(1).Column + 1, _
Criteria1:="=" & ACell.Text
Else
MsgBox "Select a cell in your List or Table before you run the macro", _
vbOKOnly, "Filter example"
End If
End Sub
Filter the first field of the Table/List for the text value of
Range("D1")
Sub FilterListOrTableData3()
'Works in Excel 2003 and Excel 2007.
Dim ACell As Range
Dim ActiveCellInTable As Boolean
Dim FilterCriteria As String
'Use this line if you want to select a cell in the Table with code.
'Application.GoTo Sheets("Yoursheetname").Range("A24")
Page 80
Document1 SSSS
Page 81
TTTT Excel VBA Introduction
Page 82
Document1 SSSS
'Use "<>Netherlands" if you want to exclude the criteria from the filter
ACell.ListObject.Range.AutoFilter Field:=1, Criteria1:="=Netherlands"
Else
MsgBox "Select a cell in your List or Table before you run the macro", _
vbOKOnly, "Filter example"
End If
End Sub
Page 83
TTTT Excel VBA Introduction
Page 84
Document1 SSSS
Page 85
TTTT Excel VBA Introduction
If you want to print a whole workbook you can use this code line
ThisWorkbook.PrintOut Or ActiveWorkbook.PrintOut
But this will not print hidden Worksheets.
You can use this macro to print hidden and visible Worksheets
Sub Print_Hidden_And_Visible_Worksheets()
'Dave Peterson
Dim CurVis As Long
Dim sh As Worksheet
For Each sh In ActiveWorkbook.Worksheets
With sh
CurVis = .Visible
.Visible = xlSheetVisible
.PrintOut
.Visible = CurVis
End With
Next sh
End Sub
Page 86
Document1 SSSS
If row 1 is a header row and you want to print it on every page then
change RW + 1 to RW + 2 and use File>Page Setup>Sheet to fill in $1:$1
in the "Rows to repeat at top: " box.
This example will add breaks every 20 rows from row 1 till the last row with data in
column A.
Sub Insert_PageBreaks()
Dim Lastrow As Long
Dim Row_Index As Long
Dim RW As Long
'How many rows do you want between each page break
RW = 20
With ActiveSheet
'Remove all PageBreaks
.ResetAllPageBreaks
'Search for the last row with data in Column A
Lastrow = .Cells(Rows.Count, "A").End(xlUp).Row
For Row_Index = RW + 1 To Lastrow Step RW
.HPageBreaks.Add Before:=.Cells(Row_Index, 1)
Next
End With
End Sub
Page 87