VBA Training Presentation
VBA Training Presentation
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.
Excel VBA
Applications
General
Programming Excel Object
Concepts Model
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.
Sub showMessage()
MsgBox "Hello World!"
End Sub
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.
Properties panel
Change module
name
Copyright © 2005 marketRx, Inc. All rights reserved.
13
Three Ways to Run Macros
Assign macro to
the button
Declaring variables
Functions
Generally an algorithm or computation
Takes any number of arguments
Often returns one value, but can create array functions for many outputs
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
Give it a name
What kind of
procedure?
Msgbox(“string”)
This will cause a Message Box to appear when the code is run
Example:
For…Next Loops
For loops will repeat a block of code for a specified number of times
Check condition after running through the loop once – Loop will always run at
least once
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:
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
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
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
Line continuation _
Comment ‘
There are a zillion useful built in functions in VBA. Learn how to find and use some
of them.
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.
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
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
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.
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.
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
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)
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.
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.
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.
Microsoft PowerPoint
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
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
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.
If we would rather use column and row numbers. For the single cell range
C2 we could write:
Cells(2,3)
Output
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
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
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
Hiding Sheets
Sheets(“DataDrop").Visible = False
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
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)
Connection
allows a
Command
may return
Recordset
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.
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
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“
cn.Close
Set cn = Nothing
Command time out: time (secs) ADO waits for command to be returned
before aborting
Example: objComm.CommandTimeout = 0. 0 means infinity.
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
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
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.
Performance considerations
The fastest way to read data in is to use cursor type Adopenforwardonly and
lock type AdLockReadOnly.
Query Results are now stored in the “arrDocID” and “arrDocName” arrays
We only show two functions here. For the complete code illustration, please refer to
accompanied “VBA Example” excel file.
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
€ 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
€ 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
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