VBA Training
CONFIDENTIAL AND PROPRIETARY INFORMATION
This presentation and the information contained herein are confidential and proprietary,
and are intended for review only by the employees of marketRx, Inc. All other reviewers
must have the prior written consent of marketRx, Inc.
Copyright © 2005 marketRx, Inc. All rights reserved.
Agenda
Visual Basic for Applications (VBA)
Visual Basic for Applications – Excel Objects
Visual Basic for Applications – Database Connectivity
Microsoft PowerPoint
Examples of all Excel functions and VBA code from this presentation can be found in the excel supplement
Copyright © 2005 marketRx, Inc. All rights reserved.
2
Visual Basic for Applications (VBA)
A macro is a short program written using VBA that can be used to carry out
a specific task
VBA is the language that Excel macros are written in. It is a programming
language that is included with all of the Microsoft Office applications e.g.
Word, Access, PowerPoint, Excel as well as others.
VBA is a subset of Microsoft Visual Basic, an extremely popular programming
language that has been around for over 10 years.
Copyright © 2005 marketRx, Inc. All rights reserved.
3
VBA
VBA=General Programming + Object Manipulation
Excel VBA
Applications
General
Programming Excel Object
Concepts Model
Copyright © 2005 marketRx, Inc. All rights reserved.
4
Create Your First Macro - Step 1
Open Visual Basic Editor by go to Tools...Macro...Visual Basic Editor or just simply press the
[Alt] and [F11] keys at the same time.
Copyright © 2005 marketRx, Inc. All rights reserved.
5
Create Your First Macro - Step 2
In the Insert menu on top of the Visual Basic Editor, select Module to open the Module window
(code window).
Copyright © 2005 marketRx, Inc. All rights reserved.
6
Create Your First Macro - Step 3
In the Module window, type the
following:
Sub showMessage()
MsgBox "Hello World!"
End Sub
Copyright © 2005 marketRx, Inc. All rights reserved.
7
Run Your First Macro
Click the Run button, , press [F5], or
go to Run..Run Sub/UserForm to run
the program
The message box pops up with the
"Hello World!" greeting.
Copyright © 2005 marketRx, Inc. All rights reserved.
8
Macro Security Levels / Virus Protection
Security levels – control how Excel
handles suspect macros.
High: causes Excel to disable all
macros either lacking a digital
signature or containing an invalid one.
Medium: Excel prompts the user to
enable the macro or not if it lacks a
digital signature. Certificates with
invalid signatures are automatically
disabled. Macros containing a valid
signature are automatically enabled.
Low: All macros are enabled.
Macros without a digital signature are
disabled by default in Excel 2000.
To enable macros, go to “Tools
Options Macro Security” and then
select “medium”.
Copyright © 2005 marketRx, Inc. All rights reserved.
9
The Macro Dialog Box
The following figure is an example of the Macro dialog box. In this dialog box,
three macros have been created.
To run a macro, you select the macro you want from the list and press the Run
button.
Copyright © 2005 marketRx, Inc. All rights reserved.
10
Visual Basic Editor
Copyright © 2005 marketRx, Inc. All rights reserved.
11
Project Explorer in Visual Basic Editor
The Project Explorer is the window
you can see to the left of the above
screenshot (the one that shows you
the two VBAProject items).
This will list each file that you have
open including any Excel add-ins and
hidden workbooks. In VBA terms each
file is referred to as a project.
Expand the Format Sales Report
Macro project by clicking on the + sign
next to it and ensure anything
underneath it is also expanded.
Copyright © 2005 marketRx, Inc. All rights reserved.
12
Properties in Visual Basic Editor
Properties panel
Change module
name
Copyright © 2005 marketRx, Inc. All rights reserved.
13
Three Ways to Run Macros
Tools Macro Macros
Put a button on the worksheet
Note that when you create the button a macro assignment dialog opens
automatically
Put a button on a toolbar
Right-click on a toolbar, then Customize Commands Macro
Copyright © 2005 marketRx, Inc. All rights reserved.
14
Assigning a Macro to a Button on a Worksheet
Form Toolbar Button created
Assign macro to
the button
Copyright © 2005 marketRx, Inc. All rights reserved.
15
Assigning a Macro to a Button on a Worksheet
Add a Button in an Excel sheet
Display the Forms toolbar.
Click the Button icon.
Click and drag the mouse pointer to specify the position and size of button.
Select the macro name you are assigning to this button from the Assign Macro
dialog box.
Click OK.
Change the Name of the Button
Highlight the button (Hit Ctrl and click on the button).
Highlight the label on the button.
Type a new name for the button.
Click outside the button.
Click the button will run the linked macro.
Copyright © 2005 marketRx, Inc. All rights reserved.
16
The Forms toolbar
In this figure, you see the Forms toolbar.
Notice the button tool on the right side of the toolbar. This button tool will
create a command button on your worksheet.
Copyright © 2005 marketRx, Inc. All rights reserved.
17
VB Stuff You Must Learn Quickly
Declaring functions and subroutines
Declaring variables
Assigning values to variables and doing calculations
Conditional Logic: If..Then..Else
Iteration: Do..Loop, For..Next
Simple communication with user via InputBox() and MsgBox() functions
Logically designing programs consisting of multiple procedures working
together to accomplish some task
Copyright © 2005 marketRx, Inc. All rights reserved.
18
Subroutines and Functions
Subroutines
Sequence of commands
DOESN’T return a value
Takes any number of arguments
Functions
Generally an algorithm or computation
Takes any number of arguments
Often returns one value, but can create array functions for many outputs
Copyright © 2005 marketRx, Inc. All rights reserved.
19
Writing Functions
You can write a function in VBA that can be called by a formula from an Excel
worksheet
Example:
Whatever you define the function as, that is how you call it from an Excel worksheet
This function takes one argument, the value to be cubed. The value to be returned
from the function must be set equal to the name of the function
Example of how to call this function from an Excel worksheet:
=Cubic(A1) Where A1 is the cell where the number to be cubed is located
Copyright © 2005 marketRx, Inc. All rights reserved.
20
Add a New Procedure/Function Through Wizard
Give it a name
What kind of
procedure?
Who can “see”
the procedure?
Copyright © 2005 marketRx, Inc. All rights reserved.
21
Passing Argument by Reference or by Value
If you pass an argument by reference when Sub TestPassing1()
calling a procedure, the procedure access to the Dim y As Integer
actual variable in memory. As a result, the y = 50
variable's value can be changed by the AddNo1 y
procedure. MsgBox y
End Sub
Passing by reference is the default in VBA. If Sub AddNo1(ByRef x As Integer)
you do not explicitly specify to pass an x = x + 10
End Sub
argurment by value, VBA will pass it by
reference. The following two statements yield
the same outcome.
Sub AddNo(ByRef x as integer) Sub TestPassing2()
Sub AddNo(x as integer) Dim y As Integer
y = 50
Here is an example to show the by reference AddNo2 y
behavior. The sub procedure, TestPassing 1 MsgBox y
calls AddNo1 by reference and display "60" (50 + End Sub
10) on the message box.
Sub AddNo2(ByVal x As Integer)
The following example shows the by value x = x + 10
behavior. The sub procedure, TestPassing 2 End Sub
calls AddNo2 by value and display "50" on the
message box.
Copyright © 2005 marketRx, Inc. All rights reserved.
22
Variables
Variables are used for temporary storage of values
Declare variables with Dim
You have to state the variables data type
The declaration have to be made before using the variable
Example: Dim NumItems As Integer
Variables do not have to be defined in VBA, but it is good programming
practice to define them
To force the definition of variables, at the top of the module window type the
following:
• Option Explicit
To force Option Explicit for all Modules: Tools Options Check “Require
Variable Declaration”
Copyright © 2005 marketRx, Inc. All rights reserved.
23
Common Data Types
String – for text like “Bob Smith”
string literals are enclosed in quotes
Integer – integers in –32768 to 32768
Long – for bigger integers
Boolean – only True (-1) or False (0)
Double – numbers with decimals
Currency – monetary values
Date – for dates and times
date literals must be like this: #1/7/2005#
Object – specific versions for each object type
Variant – let VBA decide how to deal with
If you don’t declare a variable, this is the default data type VBA will use.
This should be avoided as much as possible.
Copyright © 2005 marketRx, Inc. All rights reserved.
24
You Should Declare Variables Yourself
They take up less memory
The code runs smoother
The code is easier to read
VBA checks for misspelled variable names
You cannot put the wrong data type into a variable
It’s good programming style
Copyright © 2005 marketRx, Inc. All rights reserved.
25
Building Blocks of Expressions
(1) Relational and Arithmetic Operators
Relational Logical (2) Logical Operators
Operator Description Operator
= Equal And
<> Non equal Or
< Less than Not
> Greater than
<= Less than or equal to Literals Example
>= Greater than or equal to Value 23
Arithmetic Text or
Operator Description String "Smith"
add, sub, div, mult,
+ - / * ^ power Date #1/1/2000#
& string concatentation Yes/No -1=TRUE=Yes
0=FALSE=No
Copyright © 2005 marketRx, Inc. All rights reserved.
26
Visual Basic for Applications – Decisions
If…Then…Else Statements can be used in VBA
Msgbox(“string”)
This will cause a Message Box to appear when the code is run
Copyright © 2005 marketRx, Inc. All rights reserved.
27
Visual Basic for Applications – Select Case
Select Case statement is an alternative to the ElseIf statement. This
method is more efficient and readable in coding than the “If ... Then ...
ElseIf” statement.
Example:
Select Case Grade
Case Is >= 90
LetterGrade = "A"
Case Is >= 80
LetterGrade = "B"
Case Is >= 70
LetterGrade = "C"
Case Is >= 60
LetterGrade = "D"
Case Else
LetterGrade = "Sorry"
End Select
Copyright © 2005 marketRx, Inc. All rights reserved.
28
Visual Basic for Applications – Loops
For…Next Loops
For loops will repeat a block of code for a specified number of times
Changing increment size in the for loop
To exit the loop early “Exit For”
Copyright © 2005 marketRx, Inc. All rights reserved.
29
Visual Basic for Applications – Loops
Do …Loop Loops -- Repeats statements while a condition is true
Check condition prior to entering loop
Check condition after running through the loop once – Loop will always run at
least once
Copyright © 2005 marketRx, Inc. All rights reserved.
30
Arrays
A variable containing a list of values of the
same data type. Values are accessed with
variable name and an index.
Before signing values to an array, the array
needs to be created. You can declare the
array by using the Dim statement.
To declare a one-dimensional array with 5
elements, type the following:
Dim Arr(5) as string
The element’s index of the array starts
from 0 unless Option Base 1 is specified
in the public area (area outside of the sub
procedure).
You can also define the array to start from
any base number, for example, dim arr(2 to
6) will define a 5-element array with index
starting from 2.
Copyright © 2005 marketRx, Inc. All rights reserved.
31
Dynamic Arrays
The ReDim statement is used to size or resize a dynamic array that has already been formally
declared.
For example, if you have already declared an array with an element value of 5 and decided to change
the number of the element to 6, you can do the following to resize the array: Redim Arr(6)
ReDim cannot change the type of the array and it can only change the bounds of the array but
not the number of its dimensions.
Each time you execute the ReDim statement, all the values currently stored in the array are
lost, unless you use “Preserve” keyword, e.g. ReDim Preserve Arr(10).
The size of an array can be determined by the value of a variable – The following code is an
example of that:
Copyright © 2005 marketRx, Inc. All rights reserved.
32
Multi-Dimensional Array
An array can also store multiple dimensional data. To simplify our tutorial, example
on a two-dimensional array is used.
Assume you have data of a local store's yearly sale in the following table and you
want to store the data in a two-dimensional array:
Year 2003 Year 2004
CD Sale 1,000 1,500
DVD Sale 1,200 2,000
First we create the array as follow: Dim Arr(2,2) as long
Then we assign the values into the array. We treat the first dimension as the year
and the second dimension as the product sale:
arr(1,1) = 1000
arr(1,2) = 1200
arr(2,1) = 1500
arr(2,2) = 2000
Copyright © 2005 marketRx, Inc. All rights reserved.
33
Size of an Array
The largest available subscript for the indicated dimension of an array can be obtained by
using the Ubound function.
UBound returns the following values for an array with these dimensions:
Dim A(1 To 100, 0 To 3, -3 To 4)
Statement Return Value
UBound(A, 1) 100
UBound(A, 2) 3
UBound(A, 3) 4
Use the LBound function to find the lower limit of an array dimension.
Statement Return Value
LBound(A, 1) 1
LBound(A, 2) 0
LBound(A, 3) -3
To get the size of an array, use the following formula:
UBound(Arr) - LBound(Arr) + 1
Copyright © 2005 marketRx, Inc. All rights reserved.
34
Useful String functions and other constructs
Left, Right, Mid – get parts of a string
Len – get the length of a string
Trim – get rid of trailing and leading spaces in a string
& - string concatenation operator
Val – converts string to number
Line continuation _
Comment ‘
There are a zillion useful built in functions in VBA. Learn how to find and use some
of them.
Copyright © 2005 marketRx, Inc. All rights reserved.
35
InputBox
InputBox – get a single value from the user
Syntax: variable = InputBox(Prompt,Title)
Variable is a variable whose value is set based on user entry.
Prompt is the message you want to appear in the input box.
Title is the text that appears in the title bar of the input box.
Salary=InputBox(“Enter your salary.”, “Application”)
Copyright © 2005 marketRx, Inc. All rights reserved.
36
Message Box
MsgBox – show user message, get button click response
Syntax: MsgBox Prompt, Buttons, Title
Prompt is the message in the dialog box
Buttons specifies the kind of buttons that appear in the message box, and the style of
the message box.
Title is the text for the title bar
Examples:
MsgBox “The macro is finished”, vbOKOnly, “Done”
MsgBox “Proceed?”, vbOKCancel, “Start Macro”
MsgBox “The macro is finished”, vbOKOnly, “Done”
Copyright © 2005 marketRx, Inc. All rights reserved.
37
Random Number
To generate random number from 0 to 1
uniformly, one can use the Rand() function
in Excel or the Rnd function in VBA.
These two functions are the mother of all
random numbers. You will need either one
Sub rndNo()
of these functions to generate random Dim str As String
numbers from any probability distributions.
Or you can use the random number
generator in Analysis ToolPack Add-ins. For i = 1 To 5
The rand() excel formula function before str = str & CStr(Rnd) & vbCrLf
Excel 2003 has a low quality of randomness.
The function was changed in Excel 2003 but
Next i
has a bug. You need to download a fix from
Microsoft. It is better to use Rnd() in VBA to MsgBox str
generate random numbers for you.
End Sub
The example on the right generates 5
random numbers and then displays them in
a message box:
* CStr() function converts the random
numbers into string.
Copyright © 2005 marketRx, Inc. All rights reserved.
38
Randomize Statement
For the previous example, when we
close the file, reopen it, and run the
sub routine again, the same 5 Sub rndNo()
numbers come up! Dim str As String
The reason why this happens is that Randomize
the random numbers were actually For i = 1 To 5
being generated from the same set of str = str & CStr(Rnd) & vbCrLf
numbers (called seed). Next i
By placing the Randomize statement MsgBox str
in the sub routine, the numbers will be End Sub
generated from a new seed.
(Randomize uses the return value
from the Timer function as the new
seed value.)
Copyright © 2005 marketRx, Inc. All rights reserved.
39
VBA Debugging
Too many programmers become complacent once the code is written and they get
a clean compile. These are only the first steps. The most important steps, and the
ones programmers like the least, are debugging and testing code.
Three types of Errors
Syntax errors: A variety of errors related to entering the code itself. These include
incorrectly spelled keywords, mismatched parentheses, etc. Excel flags your syntax
errors and you can't execute your code until they are correct.
Run-time errors: These are the errors that occur while your code is executing. For
example, if your code refers to an object that doesn't exist, you'll get a run-time error.
Excel displays a message when there is a run-time error.
Logical errors: These are errors that occur through faulty programming. In many cases
they will simply produce incorrect results.
Debugging your code is the process of finding and correcting run-time errors and
logical errors
We will describe the various debugging resources available in the Visual Basic
Editor (VBE) and how to use them.
These are basic descriptions of the various diagnostic tools and how to use them. See
the on-line help for more details.
Copyright © 2005 marketRx, Inc. All rights reserved.
40
Debug Message Box
The most common use of the
debugger is to diagnose the code
when a crash is encountered. If no
error handling is in place, when an
Access application crashes, you or
your user are prompted with an End,
Debug message box:
Copyright © 2005 marketRx, Inc. All rights reserved.
41
Break Points
A break point is a setting on a line of code that tells VBA to pause execution
immediately before that line of code is executed. Code execution is placed in what
is called break mode.
When a line contains a break point, it is displayed with a brick colored background.
Immediately before this line of code is executed, it will appear with a yellow background.
When VBA is in break mode, you can enter commands in to the Immediate Window
to display or change the values of variables.
To put a break point on a line of code, place the cursor on that line and press F9 or
choose "Toggle Breakpoint" from the Debug menu.
To remove a break point, place the cursor on the line with the break point and press
F9 or choose "Toggle Breakpoint" from the Debug menu.
After a break point is encountered, you can resume normal code execution by
pressing F5 or choosing "Continue" from the Run menu, or stepping through the
code line by line (see next slide).
Copyright © 2005 marketRx, Inc. All rights reserved.
42
Break Mode
Copyright © 2005 marketRx, Inc. All rights reserved.
43
Stepping Through Code
Normally, your code runs unattended. It executes until its logical end. However, when you are
testing code, it is often useful to step through the code line by line, watching each line of code
take effect. This makes it easy to determine exactly what line is causing incorrect behavior.
You can step through code line by line by pressing the F8 key to start the procedure in which
the cursor is, or when VBA is paused at a break point.
Pressing F8 causes VBA to execute each line one at a time, highlighting the next line of code
in yellow. Note, the highlighted line is the line of code that will execute when you press F8. It
has not yet been executed.
If your procedure calls another procedure, pressing F8 will cause VBA to step inside that
procedure and execute it line by line. You can use SHIFT+F8 to "Step Over" the procedure
call. This means that the entire called procedure is executed as one line of code. This can
make debugging simpler if you are confident that the problem does not lie within a called
procedure.
When you are in a called procedure, you can use CTRL+SHIFT+F8 to "Step Out" of the
current procedure. This causes VBA to execute until the end of the procedure is reached (an
End Sub or Exit Sub statement) and then stop at the line of code immediately following the
line which called the procedure.
Copyright © 2005 marketRx, Inc. All rights reserved.
44
Stepping Through Code
VBA also supports "Run To Cursor". This is exactly what it sounds like. It tells VBA
to execute code until the line on which the cursor is sitting is reached. When this
line is reach, VBA enters break mode.
This is similar to putting a break point on a line of code, except that the break point is
temporary. The second time that line of code is executed, code execution does not
pause.
Set Next Statement [Ctrl+F9] This command lets you set the next statement as
any line in the current procedure including lines you’ve already run.
This is extremely powerful and quite amazing when you think about it. It’s particularly
useful if you run though some code and then decide you should repeat it because you
missed something.
It’s not always the same as the first run because variables may have changed, but if you
understand the situation, it lets you debug again without getting to the same code or
situation again.
Show Next Statement Sometimes you examine different procedures as you debug
your code, so the Show Next Statement menu command makes it easy to go to the
currently highlighted line.
Copyright © 2005 marketRx, Inc. All rights reserved.
45
Immediate Window
The Immediate Window is a window in the VBE in which you can enter commands and
view and change the contents of variables while you code is in Break mode or when no
macro code is executing.
Break mode is the state of VBA when code execution is paused at a break point (see Breakpoints,
below.
To display the Immediate Window, press CTRL+G or choose it from the View menu.
In the Immediate Window, you can display the value of a variable by using the ?
command. Simply type ? followed by the variable name and press Enter. VBA will display
the contents of the variable in the Immediate Window. For example,
?ActiveCell.Address
$A$10
You can also execute VBA commands in the Immediate Window by omitting the question
mark and entering the command followed by the Enter key:
Application.EnableEvents=True
or
Range("A1").Value = 1234
Copyright © 2005 marketRx, Inc. All rights reserved.
46
Locals Window
The Locals Window displays all the
variables in a procedure (as well as
global variables declared at the
project or module level) and their
values.
This makes it easy to see exactly what
the value of each variable is, and
where it changes, as you step through
the code.
You can display the Locals Window by
choosing it from the View menu.
The Locals Window does not allow
you to change the values of variables.
It simply displays their names and
values.
Copyright © 2005 marketRx, Inc. All rights reserved.
47
Watch Window
The Watch Window allows you to
"watch" a specific variable or Three watch types
expression and cause code execution
to pause and enter break mode when
the value of that variable or
expression is True (non-zero) or
whenever that variable is changed.
To display the Watch Window, choose
it from the View menu. To create a
new watch, choose Add Watch from
the Debug menu. This will display the
Add Watch window, shown on the
right.
Copyright © 2005 marketRx, Inc. All rights reserved.
48
Writing Code for Debugging
You can use the Debug.Print statement anywhere in your code to display
messages or variable values in the Immediate Window. These statements
don't require any confirmation or acknowledgement from the user so they
won't affect the operation of your code.
'
' some code
'
Debug.Print "Starting Code Section 1"
In Excel 2000 and later, you can use Debug.Assert statements to cause
the code to break if a condition is not met. The syntax for Debug.Assert
is: Debug.Assert (condition)
Example
Dim X As Long
X = 123
Debug.Assert (X < 100)
Copyright © 2005 marketRx, Inc. All rights reserved.
49
Eight Bug Reduction Tips
You cannot completely eliminate bugs in your programs, but there are a few tips
that will help you keep them to a minimum.
Use an Option Explicit at the beginning of your module. Doing so will require
that you define the data type for every variable that you use. It's a bit more work,
but you'll avoid the common error of misspelling a variable name.. And there's a
nice side benefit: Your routines will often run faster.
Format your code with indentation. Using indentation to delineate code
segments is quite helpful. If you have several nested For...Next loops, for example,
consistent indentation will make it much easier to keep track of them all.
Be careful with On Error Resume Next. This statement causes Excel to ignore
any errors and continue. In some cases, using this statement will cause Excel to
ignore errors that shouldn't be ignored. Your may have bugs and not even realize it.
Use lots of comments. Nothing is more frustrating than revisiting code that you
wrote six months ago - and not having a clue as to how it works. Adding a few
comments to describe your logic can save you lots of time down the road.
Copyright © 2005 marketRx, Inc. All rights reserved.
50
Eight Bug Reduction Tips
Keep your subroutines and functions simple. Writing your code in
smaller modules, each of which has a single, well-defined purpose, makes
it much easier to debug them.
Use the macro recorder to help you identify properties and methods.
If I can't remember the name or syntax of a property or method, it's often
quicker to simply record a macro and look at the recorded code.
Consider a different approach. If you're having trouble getting a
particular routine to work correctly, you might want to scrap the idea and
try something completely different. In most cases, Excel offers several
alternative methods of accomplishing the same thing.
Understand Excel's debugger. Although it can be a bit daunting at first,
you'll find that Excel's debugger is an excellent tool. Invest some time and
get to know it.
Copyright © 2005 marketRx, Inc. All rights reserved.
51
Agenda
Visual Basic for Applications (VBA)
Visual Basic for Applications – Excel Objects
Visual Basic for Applications – Database Connectivity
Microsoft PowerPoint
Copyright © 2005 marketRx, Inc. All rights reserved.
52
Excel and Objects
Excel (and the other Office applications) consists of a number of object.
An object can be a cell, worksheet, or Excel application.
Macro programming is actually just manipulation of these objects.
When you understand the basic principle, it’s easier to learn how to
program other Office programs.
Definition of an object
An object is a named part of a computers memory.
It has certain features or properties. Like some people have brown hair, others
red hair.
It has some functionality or methods. Like people are able to walk or cars able to
drive.
Objects can contain other objects.
Copyright © 2005 marketRx, Inc. All rights reserved.
53
Properties of Objects
Properties- the attributes that distinguish an object.
To change the property of an object, use the syntax in VBA:
object.property = expression
Worksheets(“Grades”).Name = “Old Grades”
changes the Name property of the “Grades” worksheet to “Old Grades.”
Range(“G5”).Value = 880.55
changes the Value property of cell G5 to 880.55.
Range(“H5”).Formula = “=G5-F4”
changes the Formula property of cell H5 to =G5-F4
Worksheets(“Sheet 1”).Visible = False
hides sheet 1. Change to True to make visible again.
Activecell.Value=15
changes the value of the active cell to 15.
Activecell.parent.name will return the name of the worksheet that the active cell is on.
Copyright © 2005 marketRx, Inc. All rights reserved.
54
Methods of Objects
A method is an action that can be performed on an object.
The syntax for applying a method is: object.method
Example: Sheets(“Table”).Delete will delete the Table sheet
Example: Range(“A1:B5”).Clear will clear the contents of A1:B5
Copyright © 2005 marketRx, Inc. All rights reserved.
55
The Objects in Excel
The mother object is called ”Application”
Application contains a number of
workbooks.
These workbooks contain sheets.
The sheets contain ranges etc.
Application, Workbooks etc contain many
other objects, properties and method.
Some objects can have properties that are
also objects.
Copyright © 2005 marketRx, Inc. All rights reserved.
56
Accessing objects
To acces a certain sheet we would write:
Application.Workbooks(”name.xls”).Sheets(”Name”)
We might not know the sheet name:
Application.Workbooks(”name.xls”).Sheets(1)
We could now give that sheet a name:
Application.Workbooks(”name.xls”).Sheets(1).Name _
= ”MyName”
All of these examples are Fully qualified references
Copyright © 2005 marketRx, Inc. All rights reserved.
57
Implicit References
If a certain workbook is already active we could write
Sheets(”theName”)
We could access a range in a sheet by writing:
Sheets(”theName”).Range(”A1”)
Or to access a range in the active sheet:
Range(”A1”)
If the range if a named range:
Range(”RangeName”)
Copyright © 2005 marketRx, Inc. All rights reserved.
58
Referencing Cells (Cont.)
Multiple ways to reference cells in VBA
Cells(row_number, column_number)
• References a single cell
Range(Cells(row_num_1, col_num_1), Cells(row_num_2, col_num_2))
• References multiple cells in the specified range
Range(“Test_Range”)
• Can reference a “Named Range” of cells defined in the excel worksheet
Named Ranges
Select the range of cells you
want to reference
Name of Range Appears Here
Copyright © 2005 marketRx, Inc. All rights reserved.
59
Referencing Cells
To access a range we could write:
Range(”A1:B16”)
For the range stretching from A1 to B16. We could also write:
Range(”A1”,”B16”)
If we would rather use column and row numbers. For the single cell range
C2 we could write:
Cells(2,3)
We can access the range from A1 to B16 by:
Range(Cells(1,1) ,Cells(16,2))
Copyright © 2005 marketRx, Inc. All rights reserved.
60
Referencing Cells (Cont.)
Gathering Input from Cells
Data in cells can be read into VBA and stored in a variable
test_var = Cells(1,1).Value
Outputting to Cells
Data can be outputted into cells from VBA
Cells(2,1) = 123456
Example:
Output
Copyright © 2005 marketRx, Inc. All rights reserved.
61
Basic Range manipulation
The value of a range can be set and read with:
Range(”A1”).Value = 123
The formula of a range can be set with
Range(”A1”).Formula = ”=AVERAGE(A1:B16)”
Set the font of a Range:
Range(”A1:B16”).Font.Bold = True
Set the color of a range:
Range(”A1:B16”).Interior.ColorIndex = 3
Copyright © 2005 marketRx, Inc. All rights reserved.
62
Formatting Cells
Recording Macros is very useful for learning the code to format cells a
particular way
Incorporate the code from the recorded macro into your code to assist in
formatting cells - eliminate any unnecessary steps excel has added in
For example, to formats Cell “A1” to have a blue background and white
bold text, the following code is generated
Can be
Reduced To
Same Result
Copyright © 2005 marketRx, Inc. All rights reserved.
63
Worksheet Functions
Deleting a Current Worksheet if it Exists
Always set “DisplayAlerts” to False prior to deleting a worksheet so that the
code is not interrupted by a confirmation dialog box
WksExists(Sheet_name) Calls another function that returns true if the Wks
Exists
Make sure to set “DisplayAlerts” back to True once the sheet is deleted
Adding a new Worksheet
By defining a new variable as a worksheet, you will be able to easily rename it
Copyright © 2005 marketRx, Inc. All rights reserved.
64
Worksheet Functions (Cont.)
Looping Through Worksheets
Useful if you want to perform a specific function to each sheet in the workbook
• Specific Formatting
• Setting Column Widths
• Protecting Cells – If you want to protect worksheets, always make sure you unprotect
the worksheets in the beginning of the code otherwise you will be asked for the
password if you try to modify them. At the end of the code you can re-protect all of
the worksheets
Example:
Copyright © 2005 marketRx, Inc. All rights reserved.
65
Useful Tips
Screen Updating
By setting Screen Updating to False, the user will not see all of the changes that the
code is doing to the workbook until it is finished running
Application.ScreenUpdating = False
Use a lots of comments
A single quote ‘ is used to comment lines of code
Hiding Sheets
Sheets(“DataDrop").Visible = False
Outputting to Specific Sheets
Sheets("Output”).Cells(17, 2) = “Territory Name”
Range(“Test_Range”).row or .column will return the row/column that the named
range is located in
Use meaningful variable names. Use at least one capital letter in variable names
If they are typed correctly, VBA will capitalize them, making it easy to spot typos
Copyright © 2005 marketRx, Inc. All rights reserved.
66
Other Useful Tips
CTRL + Space
Brings up an auto complete menu that includes user defined functions and
variables after typing only a few letters
Turning off “Auto Syntax”
If a line of code is unrecognized in VBA, you will get a message box alerting
you
• This becomes an annoyance if you want to move away from the line of code before
you finish typing it
To turn off: Tools Options Uncheck “Auto Syntax Check”
Use white space to separate logic blocks
Make sure to lower the “Macro Security” level to medium in Excel
otherwise you will not be able to enable the use of macros
In Excel: Tools Macro Security Medium
Copyright © 2005 marketRx, Inc. All rights reserved.
67
Agenda
Visual Basic for Applications (VBA)
Visual Basic for Applications – Excel Objects
Visual Basic for Applications – Database Connectivity
Microsoft PowerPoint
Examples of all Excel functions and VBA code from this presentation can be found in the excel supplement
Copyright © 2005 marketRx, Inc. All rights reserved.
68
ActiveX Data Objects (ADO)
Open Database Connectivity (ODBC)
and OLE DB is the underlying
technology, application programming
interface (API) that interfaces between
our programs and the source of data,
such as Access, SQL Server, Oracle,
etc.
Used in Windows C and C++
programming
ADO are ActiveX objects that provides
easy access to the OLE DB and
ODBC functionality.
Used in Visual Basic and Java.
Microsoft Data Access Components
(MDAC) ties it all together by
packaging ADO with the necessary
OLE DB providers
Copyright © 2005 marketRx, Inc. All rights reserved.
69
ADO Object Model
The diagram below shows the objects.
Three objects you need
know
Copyright © 2005 marketRx, Inc. All rights reserved.
70
Relationship of ADO Objects
Connection
allows a
Command
may return
Recordset
Copyright © 2005 marketRx, Inc. All rights reserved.
71
Add ADO References in Excel
Microsoft ActiveX Data Objects 2.x Library
The latest version is 2.8.
Copyright © 2005 marketRx, Inc. All rights reserved.
72
ADO Objects
Connection object
The Connection object sets up a link between your program and the data source. This
object contains all of the necessary configuration information and acts as a gateway for
all of the other ADO objects.
Command object
The Command object executes SQL strings, stored procedures, or action queries.
Command objects may have an associated collection of Parameter objects that provide
additional information to the data source when executing the command.
Recordset object
Recordset object creates and manages a collection of records. It contains navigational
methods to move to a particular record.
Each Recordset object is composed of a number of Field objects that represent individual
columns in the Recordset.
Each command execution results in a Recordset containing the results of the query.
Copyright © 2005 marketRx, Inc. All rights reserved.
73
Connection Object
Create connection object
Dim objConn As ADODB.Connection
Set objConn = New ADODB.Connection
ObjConn.Open =”DSN=myDSN;UID=master;PWD=slave”
Close a connection
objConn.Close
SET objConn=Nothing
Connection String - designates data source name and tells which provider is being
used.
ODBC data source name: DSN = myDSN. This is used when connecting to SQL Server.
Text string
• Access: Provider=Microsoft.Jet.OLEDB.3.51;Persist Security Info=False;Data Source=C:\My
Documents\CP3013\demodb.mdb
• SQL Server: Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Data
source=[SQL Server machine name];Initial Catalog=[database name];
• It may also include information on user name and password
Copyright © 2005 marketRx, Inc. All rights reserved.
74
Create a DSN to SQL Server
Copyright © 2005 marketRx, Inc. All rights reserved.
75
Connection Example
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
cn.ConnectionString = "DSN=Demodsn” 'or
'cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Persist _
Security Info=False;Data Source=C:\My _
Documents\CP3013\demodb.mdb"
cn.Open 'or
'cn.Open = "DSN=Demodsn“
'Code creating recordset accessing data source
cn.Close
Set cn = Nothing
Copyright © 2005 marketRx, Inc. All rights reserved.
76
Command Object
Two ways to create a Command object:
Way 1:
Set objCmd = new ADODB.Command
Set objCmd.ActiveConnection = objConn
objCmd.CommandText=”qryPhoneMessagesFor”
Way 2:
objCmd.ActiveConnection = “dsn=intranet” Or
objCmd.ActiveConnection = ”DRIVER={Microsoft Access
Driver(*.mdb)}; DBQ=c:\data\…..\XXX.mdb”
Both Command and Connection objects have a method named Execute.
Syntax: .Execute (RecordsAffcted, Parameters, Options)
Give it an SQL command (as a parameter) and it creates a Recordset object.
The Recordset object contains the result of the SQL query.
Set result=objCmd.Execute("SELECT * FROM Password")
Resulting Recordset object
Copyright © 2005 marketRx, Inc. All rights reserved.
77
Command Object (Cont.)
Command time out: time (secs) ADO waits for command to be returned
before aborting
Example: objComm.CommandTimeout = 0. 0 means infinity.
Command type specifies the type of command object to be or being used,
types are
adCmdText: Evaluates CommandText as a textual definition of a command
or stored procedure call.
adCmdTable: Evaluates CommandText as table name whose columns are
all returned by internally generated SQL query.
adCmdStoredProc: Evaluates CommandText as a stored procedure name.
adCmdUnknown: Default. The type of command in the CommandText
property is not known
Copyright © 2005 marketRx, Inc. All rights reserved.
78
Recordset Object
The recordset object has its own methods and properties to retrieve data
First need to create new instance of object
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Use properties to specify connection, record source and recordset type
For Connection could put
rs.ActiveConnection = cn ‘cn is open connection or
rs.ActiveConnection = “DSN=Demodsn” ‘Opens own connection to database
Use recordset’s ‘Open’ method to populate recordset with data
Set rs = New ADODB.Recordset
rs.ActiveConnection = cn
rs.Source = SQLStatement
rs.Open
Or: Set rsobject = cnobject.Execute(SQL statement)
Copyright © 2005 marketRx, Inc. All rights reserved.
79
Recordset Object Methods
A RecordSet object holds a collection of records (from the database) and
has some methods:
EOF() : boolean that indicates there are no more records.
MoveNext(): moves to the next record
MovePrevious(): move to previous record
MoveFirst(): move to the first record
GetRows(): Fetches a block of rows into an array. Very efficient when retrieving
a big data set into memory.
Lots more…
Copyright © 2005 marketRx, Inc. All rights reserved.
80
Looping Over All Records Returned
Without “MoveNext”, this code will run forever.
Recordset object should be closed once you finishes it.
Copyright © 2005 marketRx, Inc. All rights reserved.
81
Recordset Object (Cont.)
Adding Data
Rst.Addnew
Rst(“field1”) = value1
Rst(“field2”) = value2
………….
Rst.Update (EX. Addcust1.html)
Updating data
Rst(“field1”) = value1
……
rst.Update(EX. Update.asp)
Delete
• rs.Delete
Batch updates
Rst.UpdateBatch
Copyright © 2005 marketRx, Inc. All rights reserved.
82
Recordset: Cursor
A cursor is what manages the set of records and the current location within
the recordset, the latter being handled by the current record pointer.
A good way to think about it is to imagine the cursor as a single row window
that can move up and down the recordset.
Cursor is very important as it determines what you can do with the
recordset.
Cursor location: determine where the cursor lives.
Certain data source, such as SQL Server, have a cursor service of their own,
whereas others, such as Access, don’t have a cursor service.
ADO has its own cursor service.
Use CursoLocation property:
• adUseServer – To let the data source manipulate the cursor
• adUseClient – To let ADO maninuplate the cursor.
The default cursor is server-based.
Copyright © 2005 marketRx, Inc. All rights reserved.
83
Recordset: Cursor Type
Determines how you can move through the recordset.
It can only be specified upon opening a recordset
Specify it using CursorType property in recordset object or as the third
parameter using .Open method
Adopenforwardonly (Value 0) Default
• The data is alive but you can only move forward.
• Cannot move backward or to specific record
Adopenkeyset (Value 1)
• The data is alive and any record read will be the most recent data.
Adopendynamic (Value 2)
• The data is alive and additions will be noticed.
• Accurate recordcount.
Adopenstatic (Value 3)
• The data is dead. It is like a snapshot of the data.
• Accurate recordcount.
Copyright © 2005 marketRx, Inc. All rights reserved.
84
Recordset: Lock Type
This affects data modification and concurrency
Lock types:
AdLockReadOnly (Value 1) Default
• Read-only recordset, no locking provided since data cannot be updated.
AdLockPessimistic (Value 2)
• Attempts to lock record once editing starts.
AdLockOptimistic (Value 3)
• Only locks the record when .Update method is used.
AdLockBatchOptimistic (Value 4)
• Locks are issued when .UpdateBatch method is used
Performance considerations
The fastest way to read data in is to use cursor type Adopenforwardonly and
lock type AdLockReadOnly.
Copyright © 2005 marketRx, Inc. All rights reserved.
85
ADO Example I
Copyright © 2005 marketRx, Inc. All rights reserved.
86
ADO Example I (Cont.)
Query Results are now stored in the “arrDocID” and “arrDocName” arrays
Copyright © 2005 marketRx, Inc. All rights reserved.
87
ADO Example I (Cont.)
Copyright © 2005 marketRx, Inc. All rights reserved.
88
ADO Example II
This is a simplified version of a real life application:
We have a list of dinner program participants with DocID stored in table T_Participants.
We have the prescription information of all physicians including those program
participants, stored in table T_Prescription.
For each participant, we would like to find a control among all non-participants who has
the closest 24th month prescription as the participant and whose scripts are no more and
less than 20 of that of this participant.
At the end, we will save all participants with their identified controls into T_matched table
with two columns: ParticipantID, and NonParticipantID.
We use this example to illustrate two things:
How you can save results back to the database.
You should always try to separate the logic into a few blocks and then put each block
into a function/procedure. This will make the whole code much easier to read and
understand.
• In this example, we split the main logic into three pieces: read data, find controls, and save data.
• Can you see how long the main() function will be if we put all code into it only?
We only show two functions here. For the complete code illustration, please refer to
accompanied “VBA Example” excel file.
Copyright © 2005 marketRx, Inc. All rights reserved.
89
ADO Example II – Main() function
Copyright © 2005 marketRx, Inc. All rights reserved.
90
ADO Example II – Matching_SaveData() function
Copyright © 2005 marketRx, Inc. All rights reserved.
91
Agenda
Visual Basic for Applications (VBA)
Visual Basic for Applications – Excel Objects
Visual Basic for Applications – Database Connectivity
Microsoft PowerPoint
Examples of all Excel functions and VBA code from this presentation can be found in the excel supplement
Copyright © 2005 marketRx, Inc. All rights reserved.
92
Using the marketRx template
The standard marketRx template can be found at
\\Filesrv\Marketing\marketingmaterial\Templates
• “Standard marketRx template - Read notes on Slide 1.ppt”
There are notes on the first slide with an explanation on how to use the
template
This should be used for all presentations created
Copyright © 2005 marketRx, Inc. All rights reserved.
93
Using Charts and Graphs from Excel
Remember to always paste tables and graphs into PowerPoint as a Picture
not as a direct paste
Ensures that data and formatting is not changed in the presentation
PAI Market Trends
€ 7,000
€ 6,000
Euros (Millions)
€ 5,000
PAI Market
€ 4,000
Brand PAI Mkt
€ 3,000
Generic PAI Mkt
€ 2,000
€ 1,000
€0
MAT 2001 MAT 2002 MAT 2003 MAT 2004
Year
MAT 2001 MAT 2002 MAT 2003 MAT 2004
PAI Market € 4,794,808,856 € 5,445,855,733 € 5,833,228,293 € 6,525,998,076
Brand PAI Mkt € 216,808,363 € 213,596,344 € 225,108,099 € 249,900,617
Generic PAI Mkt € 4,578,000,493 € 5,232,259,389 € 5,608,120,194 € 6,276,097,459
Brand - % of Mkt 4.52% 3.92% 3.86% 3.83%
Copyright © 2005 marketRx, Inc. All rights reserved.
94
Resizing and Cropping Images
By adding the picture toolbar (Right Click on the toolbar Click on
“Picture”) you can select the “Crop” option
This will allow you to crop off certain areas of the picture you paste
Resizing Pictures
You can also right click on the picture and click on “Format Picture”
The size tab will allow you to keep graphs and tables pasted from Excel the
same size throughout the presentation
€ 7,000
€ 6,000
Euros (Millions)
€ 5,000
€ 4,000
€ 3,000
€ 2,000
€ 1,000
€0
MAT 2001 MAT 2002 MAT 2003 MAT 2004
Year
Copyright © 2005 marketRx, Inc. All rights reserved.
95
Aligning Object in PowerPoint
PowerPoint has several features that will help maintain the consistency of the
placement of objects on slides throughout the presentation
Centering an object on the slide
In the lower left hand corner of PowerPoint, there is a “Draw” menu
• Draw “Align or Distribute” “Relative to Slide”
• Draw “Align or Distribute” “Align Center” : This will center the object horizontally on the
page
• Draw “Align or Distribute” “Align Middle” : This will center the object vertically on the page
If there are multiple objects to align on the page, “Drawing Guides” are more useful
Right click on the slide: Click “Grid and Guides” and Check “Display Drawing Guides on
Screen”
• This place one centered vertical and one centered horizontal line on the slides
• These lines can be duplicated (Click on the line, hold “Ctrl” and drag the line to a new position
• By aligning these with objects in your presentation, it will help to maintain consistency
By Holding “Ctrl” and using the arrow keys, you will have greater control over the
movement of the picture on the slide
Copyright © 2005 marketRx, Inc. All rights reserved.
96