Anda di halaman 1dari 20

Visual Basic for

Finance

Disclaimer: Tykoh Group ("Tykoh") disclaims all warranties of quality, accuracy, correctness, or fitness for a
particular purpose. The user assumes the entire risk as to the quality , accuracy and correctness of this work. The
user assumes the entire risk as to consequences of any actions user may take or not take as a result of anything
in this work. In no event will Tykoh be liable for any indirect, special, or consequential damages.
This work may not be reproduced in whole or in part by any means nor posted to a website or stored in any
medium without the express written permission of Tykoh.

Copyright 2009 Tykoh Group Pty Limited


All rights reserved
www.tykoh.com
-1

Visual Basic for Finance


Contents

Introduction to this workshop ........................................................................................6


Macros and Add-Ins.......................................................................................................8
Introduction to Macros and Add-Ins..........................................................................8
Macros in a personal workbook.................................................................................8
Recording a keyboard shortcut ..............................................................................8
Running a macro - from a keyboard shortcut ......................................................10
Changing a keyboard shortcut .............................................................................11
Changing a macro name.......................................................................................12
Moving your personal workbook from one PC to another ..................................17
Macros in other workbooks .....................................................................................19
Recording and running a macro ...............................................................................20
Running a macro - from the Main Excel menu....................................................21
Running a macro - from a custom menu item......................................................22
Sharing macro workbooks - menu items .................................................................28
The auto_open macro...............................................................................................31
Creating an Add-In ..................................................................................................33
Creating an Add-In ..............................................................................................33
Setting an Add-In to load automatically ..................................................................34
Updating an Add-In .............................................................................................37
Password protecting an Add-In................................................................................44
Setting a Visual Basic password ..........................................................................44
Disabling Add-Ins....................................................................................................47
Macro Security.........................................................................................................48
Password protection .............................................................................................48
Security levels......................................................................................................48
Signing macros.....................................................................................................50
Lowering macro security .....................................................................................52
Safe and unsafe macros........................................................................................52
Add-In security ........................................................................................................52
Macro attachments in emails ...................................................................................52
Using the Visual Basic Development Environment ....................................................53
Introduction to the IDE ............................................................................................53
Developing code ......................................................................................................53
Setting breakpoints...................................................................................................54
Single stepping.........................................................................................................56
Programming................................................................................................................59
Variables ..................................................................................................................59
Variable Names....................................................................................................59
Variable Types .....................................................................................................59
Default values of variables...................................................................................62
Declaring variables is optional.............................................................................62
Statements ................................................................................................................63
Several statements on one line.............................................................................64
One statement on several lines.............................................................................64
Statements as programs........................................................................................65
Program flow / order of statements..........................................................................65
If statement...............................................................................................................65
Copyright 2009 Tykoh Group Pty Limited
All rights reserved
www.tykoh.com
-2

Visual Basic for Finance


Contents

Iif statement .............................................................................................................66


Select Case statement...............................................................................................67
For statement............................................................................................................67
For Each statement...................................................................................................69
While statement .......................................................................................................69
Do While statement..................................................................................................70
Do Until ...................................................................................................................70
Do Loop ...................................................................................................................70
Calling functions and Subroutines ...........................................................................71
Arguments - passing by reference........................................................................72
Arguments - passing by value..............................................................................73
Exit Sub and Exit Function statement......................................................................73
On Error statement...................................................................................................74
On Error Resume Next error handler...................................................................75
On Error GoTo error handler ...............................................................................76
Arrays.......................................................................................................................78
Two dimensional arrays ...........................................................................................79
The Collection object...............................................................................................79
Collection keys.....................................................................................................80
Strings ......................................................................................................................81
Joining strings (concatenation) ............................................................................81
The split function .................................................................................................81
The Left function .................................................................................................82
The Right function ...............................................................................................82
The Mid function .................................................................................................82
The len function ...................................................................................................83
Worksheet functions ................................................................................................83
The Object Model ........................................................................................................84
Introduction to the Object Model.............................................................................84
Object Model syntax ............................................................................................84
Object model - Intellisense - walkthrough...............................................................84
Object model - Intellisense - another walkthrough..................................................89
Properties and Methods............................................................................................92
Recording macros to learn about the Object Model ................................................94
The Range Object ..................................................................................................100
The Rows property.................................................................................................101
The Columns property ...........................................................................................102
The Cells property..................................................................................................103
The End property ...................................................................................................103
The Offset property................................................................................................105
The Selection property...........................................................................................105
Object Model exercises..........................................................................................105
Controls......................................................................................................................108
Introduction to controls..........................................................................................108
The button control..................................................................................................109
The checkbox control.............................................................................................110
The drop-down control ..........................................................................................116
Copyright 2009 Tykoh Group Pty Limited
All rights reserved
www.tykoh.com
-3

Visual Basic for Finance


Contents

Forms .........................................................................................................................126
Introduction to forms .............................................................................................126
Message Boxes...................................................................................................126
Inbuilt Forms..........................................................................................................127
The GetOpenFile dialog.....................................................................................127
The SaveFileAs dialog.......................................................................................129
The FileDialog dialog ........................................................................................129
User Forms.............................................................................................................130
Functions....................................................................................................................138
Introduction to functions........................................................................................138
Function example - A single range argument ........................................................145
Function example - An optional second argument ................................................146
Function example - Three optional arguments ......................................................147
Function Example - Returning an array.................................................................147
Improving the function ......................................................................................150
Limitations of Functions ........................................................................................151
Events.........................................................................................................................153
Introduction to events ............................................................................................153
Workbook events ...............................................................................................153
The SheetSelectionChange event.......................................................................155
The BeforeSave event ........................................................................................156
Worksheet Events ..................................................................................................158
The FollowHyperlink event ...................................................................................158
Classes........................................................................................................................162
Introduction to Classes...........................................................................................162
A queue class .........................................................................................................163
Class Interface....................................................................................................165
Public and Private access ...................................................................................166
Design Principles .......................................................................................................169
Introduction to design principles ...........................................................................169
Minimise unnecessary dependencies .....................................................................169
Use a naming convention.......................................................................................170
Keep procedures short............................................................................................171
Keep scope of variables as small as possible.........................................................171
Keep as many things private as possible................................................................171
Try to have only one exit point from a procedure .................................................171
Test your work .......................................................................................................172
Use Option Explicit................................................................................................172
Office integration .......................................................................................................173
Introduction to Office integration ..........................................................................173
Integrating with Word............................................................................................173
Type and Object libraries...................................................................................173
Object libraries and portability ..............................................................................178
Late binding versus early binding..........................................................................179
Using early and late binding ..............................................................................182
Copying tables and charts from Excel to Word .................................................183
Integrating with PowerPoint ..................................................................................185
Copyright 2009 Tykoh Group Pty Limited
All rights reserved
www.tykoh.com
-4

Visual Basic for Finance


Contents

Integrating with Internet Explorer .........................................................................188


Integrating with Outlook........................................................................................190
Index ..........................................................................................................................192

Copyright 2009 Tykoh Group Pty Limited


All rights reserved
www.tykoh.com
-5

Visual Basic for Finance


Introduction to this workshop

Introduction to this workshop


This workbook is used in a two day workshop "Visual Basic for Finance" conducted
internationally by Tykoh Training. See www.tykoh.com for more information about
the workshop.
Visual Basic is part of most Microsoft Office applications and is a powerful - but
often underutilised tool. With it you can:

Automate routine work and save the time and trouble of doing the same thing
over and over

Increase work efficiency by making shortcuts for common tasks

Customize Office products to your needs by extending or changing those


products' functionality

Integrate workflows across Office applications

Increase the "wow-factor" of your developed applications

The intended audience for this workbook is the Microsoft Office "power-user" who
wants to exploit the power and potential of Visual Basic.
Visual Basic has many features and new users can be daunted by its size and scope.
This workbook - and the workshop in which it is used - attempts to focus on those
parts of Visual Basic that are the most immediately useful for business and finance.
We study Visual Basic applications in Excel, Word, Outlook and PowerPoint individually and in combination. Most of the emphasis though will be on Excel.
Excel 2007's user interface changed significantly from Excel 2003's. The underlying
Visual Basic however remains much the same. In this workshop we use the 2003
version of Office.
In this workbook we use special symbols for particular purposes. The following
symbol represents an action you need to take.
An action to do.

You can tick in the action box


keep track of what you're up to.

when you've finished the action so you can easily

The following symbol is a question you need to answer.

Question

A question to answer.
Copyright 2009 Tykoh Group Pty Limited
All rights reserved
www.tykoh.com
-6

Visual Basic for Finance


Introduction to this workshop

And this symbol is an Exercise you're asked to do.

Exercise

An exercise to carry out.

Some of the exercises are followed by answers. An answer section looks like this.

#Answer

The answer section will be blank. However, the workshop presenter's version of these
notes will have the blank sections filled out and they will be revealed on-screen at the
appropriate time in the workshop.
In working through this book you'll frequently need to navigate to certain menu items.
The notation we use for menu navigation is like this: Tools | Macro | Record New
Macro. That means you should select the "Tools" menu item, then the "Macro" submenu item and then the "Record New Macro" sub-sub-menu item.
In these notes we sometimes refer to a reference spreadsheet. The spreadsheet is
Tykoh-VBA-Reference.xls and is downloadable from www.tykoh.com/xls/TykohVBA-Reference.xls
You have been provided with a number of exercise files and those are all in the folder
C:\Program Files\Tykoh\Courses\Visual Basic for Finance. You will have a shortcut
on your desktop named "Visual Basic" that will refer to the preceding folder. At the
conclusion of the workshop you'll be given the model answers to the exercises.

Copyright 2009 Tykoh Group Pty Limited


All rights reserved
www.tykoh.com
-7

Visual Basic for Finance


Macros and Add-Ins

Macros and Add-Ins


Introduction to Macros and Add-Ins
Macros are a central part of Visual Basic. A macro is a set of actions within an Office
Application. The action can be relatively simple: To print a page; or it can be
complex: For example to extract information from an Excel workbook and put a
summary into a Word document. Macros can be "recorded" and "played back". Or
they can be written. Or a combination of the two.
In this section we look at Macros and see how they are created, where they can be put
and how they can be shared. We also introduce macro security.

Macros in a personal workbook


Some macros may benefit a group of people. A macro that formats a chart to a
"company style" for example is of common benefit. Other macros however might
have a more personal nature. Such macros can be put into a special Excel workbook
named Personal.xls.
In the following sections we'll look at how to set up and maintain Personal.xls.
We'll begin by looking at how we can add keyboard shortcuts to Personal.xls. A
keyboard shortcut consists of the Ctrl key together with another key. The shortcut
represents a useful set of Office actions. For example, the Ctrl and f keys (Ctrl+f
together) might format a cell or part of a document. The actions associated with a
keyboard shortcut can be recorded. The set of recorded actions is a "macro". And the
macros in Personal.xls can be a store of useful and frequently used actions.
You may or may not have Personal.xls on your PC. If you don't have Personal.xls
the easiest way to create it is to record a macro. That is what we will do next.

Recording a keyboard shortcut


We'll record a keyboard shortcut Ctrl+r to set the text red in whichever cells are
currently selected.
We'll begin by initialiasing the worksheet before starting the macro recorder.

Open Excel.
Select a cell and type some text into it. Make sure you don't
change which cell is selected while you do the following
steps.

Next we'll start the macro recorder.


Copyright 2009 Tykoh Group Pty Limited
All rights reserved
www.tykoh.com
-8

Visual Basic for Finance


Macros and Add-Ins

Select Tools | Macro | Record New Macro

You should see something like this.

Set the macro name to SetCellRed


Set the shortcut key to r
Make sure the "Store macro in" choice is set to "Personal Macro
Workbook".
Your Record Macro dialog should now look like this.

Press the OK button.


The macro recorder is now on and will record all of your actions in Excel.
Next we'll perform the Excel actions we want recorded.
Set the text color of the selected cell to red (make sure not to select any
other cell though).
The last step in recording is to stop the macro recorder.
Copyright 2009 Tykoh Group Pty Limited
All rights reserved
www.tykoh.com
-9

Visual Basic for Finance


Macros and Add-Ins

Select Tools | Macro | Stop Recording. Alternatively press the stop


recording button.
You have now recorded a macro and linked it to the keyboard shortcut Ctrl+r

Running a macro - from a keyboard shortcut


You now should be able to run the recorded macro by using the keyboard shortcut
Ctrl + r to set red whichever cell or cells are selected. You could set the colour of a
single cell, a single block of cells or a set of different cells. We'll do the last of these.
Put text into several cells.

Hold down the Ctrl key and then successively select the cells you typed
in earlier.
Your selection should be grayed

Press the Ctrl + r keyboard shortcut and the text in all of the selected
cells should turn red.

Exercise

In a similar way to before record a macro to set the currently


selected cells to bold font. Name the macro SetBold and give it
a keyboard shortcut Ctrl + b.
Copyright 2009 Tykoh Group Pty Limited
All rights reserved
www.tykoh.com
- 10

Visual Basic for Finance


Macros and Add-Ins

Exercise

Also record a macro to set the currently selected cells to italic


font. Name the macro SetItalic and give it a keyboard shortcut
Ctrl + i.

Exercise

Last, record a macro to set the text colour to "Automatic".


Name the macro SetAutomatic and give it a keyboard shortcut
Ctrl + a.

Exercise

After you have recorded the macros try them out and check that
they work as they should.

Changing a keyboard shortcut


Sometimes you might want to change a macro shortcut. You might, for example,
have a macro "SetCellRed" whose name you want to change to "SetCellTextRed".
You might want to do that so you can add another macro later "SetCellPatternRed".
In this section we'll show how to change macro shortcuts after they have been
recorded. We'll show how to do this with our earlier SetRed macro. We'll first
change the keyboard shortcut that runs the macro and then we'll change the name of
the macro.
We'll change the shortcut key that sets a cell red from Ctrl + r to Ctrl + R.
Select Tools | Macro | Macros.
A dialog box should appear which lists all of the macros currently available

Select the SetCellRed macro and then press the Options button.

Copyright 2009 Tykoh Group Pty Limited


All rights reserved
www.tykoh.com
- 11

Visual Basic for Finance


Macros and Add-Ins

Another dialog will appear showing the Macro Options.

You can now change the macro shortcut key and description.
Press the Shift and R keys and the macro options will update to show
the new shortcut

If you wanted to, you could also change the macro description.
Press the OK button. Your macro should now have the new shortcut.
Check the new shortcut works as it should

Changing a macro name


Next we will change the macro name. We'll make the name more precise and
specific. We'll change the name from SetCellRed to SetCellTextRed. In order to do
this we'll need to edit the macro.

Select Tools | Macro | Macros to bring up the Macro dialog.


Select the SetCellRed item and press the Edit button.

Copyright 2009 Tykoh Group Pty Limited


All rights reserved
www.tykoh.com
- 12

Visual Basic for Finance


Macros and Add-Ins

An error message will appear ..

Personal.xls is a "special" workbook in that it is hidden by default. To edit the macro


we will first need to unhide it.
Press OK on the error message dialog and then press Cancel on the
Macro dialog.
Go to the main Excel menu and choose Window | Unhide

After you select Unhide the Unhide dialog box will appear ..

Make sure Personal.xls is selected and press OK.


Copyright 2009 Tykoh Group Pty Limited
All rights reserved
www.tykoh.com
- 13

Visual Basic for Finance


Macros and Add-Ins

Excel will then activate the Personal.xls workbook.

Now we can return to our original goal of changing the name of the SetCellRed macro
to SetCellTextRed.
In the main Excel Toolbar select Tools | Macro | Macros.
Select the SetCellRed macro and press the Edit key

You should now see a screen that looks something like this ..

Copyright 2009 Tykoh Group Pty Limited


All rights reserved
www.tykoh.com
- 14

Visual Basic for Finance


Macros and Add-Ins

This screen has several parts and we'll focus on the parts in turn.

The highlighted area in the preceding diagram is the "Project Explorer" window. It
shows what workbooks and Excel Add-Ins are currently accessible to Visual Basic.
In your PC or laptop there may be more or different workbooks and Add-Ins. Here
we'll consider only the workbooks listed in the preceding project explorer. We'll
consider them in turn.
ATPVBAEN.XLA
This is a Microsoft provided Excel Add-In and contains a number of advanced Excel
functions like XNPV.
FUNCRES.XLA
This is another Microsoft addin.
Book2
This is the current Workbook Book2.xls. Visual Basic can "see" three worksheets
within the Workbook
Personal.xls
This is the workbook that contains the keyboard shortcuts we defined earlier. Inside
that workbook are one or more modules and our keyboard shortcuts will be in one of
the modules. The macro we are interested in - SetCellRed - is displayed on the right
side of the screen ..

Copyright 2009 Tykoh Group Pty Limited


All rights reserved
www.tykoh.com
- 15

Visual Basic for Finance


Macros and Add-Ins

We want to change the macro name from SetCellRed to SetCellTextRed.


Change the name from SetCellRed to SetCellTextRed in the same way
as you'd change a word in a document.
Next save the updated version.
Select File | Save in the Visual Basic menu

Next, close the VB window and return to Excel.

Then re-hide the Personal.xls window by selecting Window |


Hide.
Last, save your workbook and close Excel.
When asked if you want to save changes in the Personal Macro
Workbook click Yes.
Copyright 2009 Tykoh Group Pty Limited
All rights reserved
www.tykoh.com
- 16

Visual Basic for Finance


Macros and Add-Ins

Exercise

In a similar way as previously change the name of the macro


SetCellItalic to SetCellTextItalic.

Exercise

Write a macro from scratch and add it to the macros already in


Personal.xls. Details about the macro are:
Name:
Action:
Shortcut:

SetCellTextPlum
Sets selected cells' colour to a plum color
Ctrl + p

Hint: You may have noticed, when looking at the


SetCellTextRed macro, that Visual Basic refers to colors by
numbers. The number for Plum is 54.
Create the macro by copying and pasting another already
existing macro and then editing it as necessary.

Moving your personal workbook from one PC to another


Moving your Personal.xls from one PC to another can be tricky. One difficulty is that
Personal.xls's location can depend on how your PC is set up so it can be difficult
finding where it is. Generally Personal.xls will be in the folder C:\Documents and
Settings\<user name>\Application Data\Microsoft\Excel\XLSTART but it may be in
another location. Also, the Application Data folder may or may not be visible to
Explorer (depending on its settings). Sometimes there are multiple Personal.xls's and
its unclear as to which is the actual one being used. These problems exist both on the
source machine (i.e. the one you're copying from) and the destination machine (i.e.
the one you're copying to). So it's not surprising that people can end up with multiple
Personal.xls's when they attempt to move it from one PC to another.
You can use the following technique to copy Personal.xls.
On the destination machine record a dummy keyboard shortcut and
save it in the Personal Workbook.

Copyright 2009 Tykoh Group Pty Limited


All rights reserved
www.tykoh.com
- 17

Visual Basic for Finance


Macros and Add-Ins

Press OK and then record a Dummy macro (e.g. just type something
into a cell). Then stop the macro recorder.
Close Excel and, when asked to save the Personal.xls file, press the
YES button.
Go to Windows Explorer and search for Personal.xls.

The search will return one or more Personal.xls's.

Find the Personal.xls search result whose "Date Modified" matches the
current date and time.
Look at the "In Folder" column for that search result. That is the folder
containing the active Personal.xls.
Now that you have found the folder on the destination PC that contains Personal.xls
you can find the folder on the source PC.
Repeat the process above on the source PC.
Close Excel on both the source and destination PCs. Copy Personal.xls
Copyright 2009 Tykoh Group Pty Limited
All rights reserved
www.tykoh.com
- 18

Visual Basic for Finance


Macros and Add-Ins

from the source machine to the destination PC.


After you've completed the above steps the destination PC should have the same
Personal.xls as the source PC.

Macros in other workbooks


Personal.xls is a useful repository for personal macros but it isn't suited for all macros.
Since Excel always opens Personal.xls when Excel starts Personal.xls is best suited
for macros you'll always need - irrespective of which other workbook(s) you have
open. If, for example, you always want to use Ctrl+f to format a cell then the logical
place for the macro is Personal.xls. But if you need macros that are project or
workbook specific then it's best those macros are put in other workbooks.
Another reason for putting macros into other workbooks is when you want to share
those macros with other users. By its nature personal.xls is an individual resource and
isn't designed for sharing with others.
In the following section we look at putting macros into other workbooks.
Suppose we occasionally print Excel reports. For some of these reports we want the
footer to have a certain format. (The footer is at the bottom part of each printed page
and is usually shown in a lighter, gray, colour.) We want to record a macro - call it
SetStandardFooter - that will set the footer format for us: The left part of the footer
should show the date, the middle section the name of the Workbook (and its folder)
and the right part of the footer should show the page number. We want to record the
macro into a workbook that we'll name GeneralMacros.xls. In the following sections
we'll show how to do this.
Before recording the macro practice setting the footer. To set the footer:

Select File | Page Setup | Header/Footer and press the Custom Footer
button. The following dialog box should appear.

Copyright 2009 Tykoh Group Pty Limited


All rights reserved
www.tykoh.com
- 19

Visual Basic for Finance


Macros and Add-Ins

Set the footer in the format described earlier (date in left section,
pathname and file in the middle section and page number in the right
section). Do that by left mouse clicking in one of the three footer
sections and then pressing one of the buttons above.
The dialog should look like the following when you have finished.

Press the OK button.


Select File | Print Preview and verify that the footer appears as it
should.
Close the preview window.
Next, remove the footer. To remove the footer bring back the
footer dialog and manually remove the contents of the left,
centre and right sections.

Now that we know how to set up the footer we'll record a macro to do the same.
Then, later, we'll be able to play the macro back.

Recording and running a macro


We'll begin by recording a macro to set the footer.

Select Tools | Macro | Record New Macro.


In the Record Macro dialog make sure the Macro name is set to
SetStandardFooter and "Store macro in" is set to "This
Workbook".

Copyright 2009 Tykoh Group Pty Limited


All rights reserved
www.tykoh.com
- 20

Anda mungkin juga menyukai