Sie sind auf Seite 1von 44

EXCEL

INTRODUCTION TO MACROS AND VBA

TABLE OF CONTENTS
CREATING A MACRO ...................................................................................................................... 1
WHAT IS A MACRO ........................................................................................................................... 1
MACRO STORAGE AND STRUCTURE .................................................................................................. 1
PLANNING YOUR MACRO .................................................................................................................. 1
RECORDING A NEW MACRO.............................................................................................................. 1
Stop Recording.......................................................................................................................... 3
RECORDING RELATIVE & ABSOLUTE REFERENCES ............................................................................ 3
Toggling Relative References ...................................................................................................3
RUNNING MACROS ......................................................................................................................... 3
EXECUTING THE MACRO VIA THE MENU (THE MACRO RUN DIALOG BOX) ............................................ 4
ATTACHING A MACRO TO A COMMAND BUTTON ON THE WORKSHEET ................................................ 4
Editing the Button ...................................................................................................................... 5
ATTACHING A MACRO TO AN IMAGE OR DRAWING OBJECT ................................................................. 5
ATTACHING A MACRO TO A TOOLBAR BUTTON .................................................................................. 5
Adding a Macro to a Custom Toolbar Button............................................................................ 5
Changing the Assigned Macro .................................................................................................. 7
ATTACHING THE MACRO TO A KEYBOARD SHORTCUT ........................................................................ 7
USING THE VISUAL BASIC TOOLBAR .......................................................................................... 9
VIEWING & EDITING MACRO CODE .............................................................................................. 9
THE VISUAL BASIC EDITOR .............................................................................................................10
PROJECT EXPLORER WINDOW........................................................................................................11
Window Elements....................................................................................................................11
PROPERTIES WINDOW ...................................................................................................................11
To navigate the Properties window .........................................................................................12
CODE WINDOW ..............................................................................................................................13
Window Elements....................................................................................................................14
DOCUMENTING MACRO CODE.........................................................................................................15
RECORDING EXTRA CODE WITHIN AN EXISTING MACRO ..................................................................16
SUBSEQUENT RECORDED MACROS ................................................................................................16
SUB-ROUTINE CALLED FROM ANOTHER MACRO..............................................................................16
TROUBLESHOOTING ....................................................................................................................17
GENERAL TIPS ...............................................................................................................................17
Comment Out Lines ................................................................................................................17
THE PERSONAL MACRO WORKBOOK ..............................................................................................18
STEPPING THROUGH A MACRO ......................................................................................................19
Break Points ............................................................................................................................20
Setting/Removing a Breakpoint...............................................................................................20
RUN TIME ERRORS ........................................................................................................................21
SECURITY AND DIGITAL SIGNATURES......................................................................................22
CHANGING THE LEVEL OF SECURITY ...............................................................................................22
DIGITAL SIGNATURES .....................................................................................................................22
Commercial Certification .........................................................................................................23
Internal Certification ................................................................................................................23
Signing a Project .....................................................................................................................23
WRITING CODE ..............................................................................................................................24
TO CREATE A NEW MACRO FROM SCRATCH WITHOUT USING THE RECORDER .....................................24
OTHER USEFUL TIPS WHEN WRITING/EDITING MACROS .....................................................................25
Inserting new Modules ............................................................................................................26
Further Tip...............................................................................................................................26
WORKING WITH CELLS AND SELECTING RANGES .............................................................................27
USING NAMED CELLS .....................................................................................................................27

Paul Watson

PROCEDURES................................................................................................................................29
MACRO, SUB ROUTINE OR PROCEDURE? ........................................................................................29
CALLING ANOTHER PROCEDURE .....................................................................................................29
EXIT SUB AND END STATEMENTS....................................................................................................30
VARIABLES ....................................................................................................................................31
DATA TYPES ..................................................................................................................................31
STATEMENTS USED TO DECLARE VARIABLES ..................................................................................32
Dim ..........................................................................................................................................32
Public.......................................................................................................................................32
SCOPE ..........................................................................................................................................33
OPTION EXPLICIT ...........................................................................................................................34
CONDITIONAL TESTING ...............................................................................................................35
IF..THEN..ELSE STRUCTURE ...........................................................................................................35
CONDITIONAL LOOPING - DO LOOP .................................................................................................36
INPUT AND TESTING TECHNIQUES ............................................................................................37
MESSAGE BOXES ...........................................................................................................................37
Example Message Boxes........................................................................................................39
INPUTBOXES ..................................................................................................................................40
InputBox Function ...................................................................................................................40
Example InputBox Function ....................................................................................................41

Paul Watson

Excel Introduction to Macros and VBA

CREATING A MACRO
WHAT IS A MACRO
A macro is the term used to describe a block of code which will perform a sequence
of actions; examples include cycling through cells removing those whose value is
greater than 5000, creating complex charts and pivot tables, copying data from one
location to another to set up reports and many other repetitive actions.
The code is written (or recorded) in Visual Basic for Applications (VBA) which is a
top-level programming language from the Basic family. It is called Visual Basic for
Applications because it uses the application (Excel) which must be open before any
macros can be executed.
Using VBA, you can fully control every aspect of Excel. You can create custom VBA
and worksheet functions, full add-in applications with custom dialog boxes (User
Forms), toolbars and menus, and even use it to control other applications such as
Word or Access from within Excel.

MACRO STORAGE AND STRUCTURE


Macros (procedures) are stored in modules, which, in turn, are stored in workbooks.
Each workbook may have many modules and each module may have many
separate macros (procedures), thus allowing for organising and grouping related
macros. All code is viewed and edited through the Visual Basic Editor which is
consistent in look and feel across all Microsoft Office applications. The shortcut to
switch between the VB Editor and Excel is ALT+F11. Alternatively, use the Visual
Basic Editor command from the Tools, Macro menu.
If an open workbook contains macros, they will be listed under Tools, Macros, and
can be run from there. Keyboard shortcuts assigned to macros will take precedence
over built in shortcuts (e.g. a macro assigned to the sequence CTRL+b would run
instead of the default apply/remove bold). If a workbook is closed but a toolbar
button has a macro assigned, the workbook containing the macro will be opened and
the macro will run when the button is clicked.

PLANNING YOUR MACRO


Planning is a vital stage in creating a successful macro, especially if you are going to
use the recorder. When creating your plan, it is best to manually step through every
stage you want the macro to repeat, noting down relevant menus, keystrokes,
selections, etc. and when you want to use relative references (those offset from the
active cell) or absolute references (a specific range reference such as C12).

RECORDING A NEW MACRO


Once the plan has been created, switch on the recorder as follows:
-

From the Tools menu, choose Macro and Record New Macro...

Paul Watson

Excel Introduction to Macros and VBA

Enter a name for the macro (up to 64 characters, no spaces, starting with a
letter)

Assign to Keyboard Shortcut key


HINT Hold the SHIFT key down whilst pressing the nominated letter,
as this uses a shortcut of CTRL+SHIFT+letter, and gives fewer
occurrences of overwriting built-in keyboard shortcuts.

Identify where the macro should be stored:


Personal Macro Workbook
A hidden file stored in the XLSTART folder (usually on the c: drive), which is
loaded each time Excel is run; great for generic macros which you want to run
with a range of different workbooks.
This Workbook
Keeps the code contained within the current project.
New Workbook

Paul Watson

Excel Introduction to Macros and VBA

Create a separate file for the code to be held in - good for building macro
library files.
-

Enter a general description for the macro

Click OK to start recording. The Stop Recording toolbar will appear


containing two buttons, Stop Recording and Relative References. The
message Recording will be visible on the status bar

STOP RECORDING
To stop the recorder:
-

Click the Stop Recording button

From the Tools menu, choose Macro, Stop Recording

or

RECORDING RELATIVE & ABSOLUTE REFERENCES


The recorder distinguishes between absolute and relative cell referencing. For
example, if you are positioned on A1, start the recorder then move down a cell
during the recording, Absolute record will identify A2 as the cell movement. Relative
record will identify the cell below the active cell. In this case, if you run the macro
from B12 the Relative recording will select B13 and the Absolute recording will
always select A2, regardless of where you run the macro from.
TOGGLING RELATIVE REFERENCES
When recording, click the Relative Record button on the Recording toolbar.
Recording using
absolute references

Recording using
relative references
(note border)

You can switch between Absolute and Relative recording at any time during a
recording.

RUNNING MACROS
There are numerous ways you can run macros:
-

Use the Accelerator key. Hold the Control key down and press the assigned
key (use Ctrl+Shift to run capital letters)

Use the menu. Choose Tools, Macro, Macros.

Paul Watson

Excel Introduction to Macros and VBA

Assign the macro to a worksheet button or Graphic object.

Assign the macro to a custom button/item on a Command Bar (Toolbar or


Menu).

Use one macro to call another one

Use events such as Workbook_Open (covered in later modules)

Create a custom Userform (covered in later modules)

EXECUTING THE MACRO VIA THE MENU (THE MACRO RUN DIALOG BOX)
The macro dialog box will display all available macros and enable the user to run,
edit, delete and change options for the selected macro.

To run a macro from the macro dialog box, the file containing the module must be
open.
-

From the Tools menu, select Macro, Macros

Select the name of the required macro

Click the Run button

ATTACHING A MACRO TO A COMMAND BUTTON ON THE WORKSHEET


Buttons can be drawn onto a worksheet that runs macros when clicked.
-

Display the Forms toolbar (View, Toolbars)

Click the Button tool

Paul Watson

Excel Introduction to Macros and VBA

Drag a box onto the sheet (hold ALT down to snap to gridlines)

When you release the mouse an Assign Macro dialog box will appear

Select the macro from the list displayed or record a new macro

EDITING THE BUTTON


Hold down the CTRL key and click on the button to select it without running the
macro or right click on the button.

ATTACHING A MACRO TO AN IMAGE OR DRAWING OBJECT


Macros can be attached to any drawing object on your worksheet.
-

Create or insert the image/drawing object

Select the object using the right mouse button

Select Assign Macro from the shortcut menu

Select the required macro from the list

Click away from the object

Next time you point to the object, the mouse will become a pointing finger. Clicking
will run the macro.

ATTACHING A MACRO TO A TOOLBAR BUTTON


All toolbars and menus (known as Command Bars) in Excel can be customised, as
can the tools and commands they contain. Macros can be assigned to the buttons
and commands.
ADDING A MACRO TO A CUSTOM TOOLBAR BUTTON
Ensure that the file containing the macro is open
-

Point to a toolbar

Click the right mouse button to display the shortcut menu, select Customize
(you can also select Tools, Customize from the main menu)

Select the Commands tab

Paul Watson

Excel Introduction to Macros and VBA

Select Macros from the Categories list

Drag the Custom Button (Smiley face) onto a Toolbar or Menu


Once released, the new item will appear

To customise:
-

Still in Customise mode, click the right mouse button on the new item

Enter a new name (this will show as a tool tip)

Select Assign Macro (at the bottom of the menu) to choose the macro that will
run from the button

Select Change Button Image to select what to use for a button/command face

Select Edit Button Image to customise the button image:

Paul Watson

Excel Introduction to Macros and VBA

Close the Customise dialog box when done


Your changes will remain with your copy of Excel

Note:
Your command bar settings are store in a file called UserName11.XLB in
C:\Documents and Settings\YourLoginName\Application Data\Microsoft\Excel (or
wherever your user settting files are stored). This should load with your profile when
you log in and run Excel. XLB files can be opened at any time.
CHANGING THE ASSIGNED MACRO
You may wish to assign a different macro to a tool.
-

Ensure that the file containing the macro is open

Point to a toolbar

Click the right mouse button (shortcut menu)

Select Customize (or select Tools, Customize from the main menu)

Select the tool on the toolbar that you wish to change

Click the right mouse button to display the shortcut menu

Select Assign Macro... and select the required macro from the list

ATTACHING THE MACRO TO A KEYBOARD SHORTCUT


If you did not assign a shortcut key when you recorded the macro or want to change
the assigned letter, you can assign a new shortcut letter at any time.
-

From the Tools menu, select Macros, Macro

Paul Watson

Excel Introduction to Macros and VBA

Select the macro name from the list

Click the Options button

Click in the CTRL + box and press SHIFT plus the letter you wish to use

Paul Watson

Excel Introduction to Macros and VBA

USING THE VISUAL BASIC TOOLBAR


The Visual Basic toolbar can be used to work with macros either directly from the
module or from other sheets in the workbook.
change security settings

design mode

run
macro

script editor

record/
stop recording

VB Editor

control toolbox

To load the toolbar from within the workbook environment, right click on a visible
toolbar and select Visual Basic.

VIEWING & EDITING MACRO CODE


To view the code, you must use the Visual Basic Editor. This is a separate
application and is consistent between all Microsoft Office applications.
-

Switch between Excel and the VB Editor by pressing ALT F11

You can also load the VB Editor as follows:


-

From the Tools menu, choose Macro, Visual Basic Editor

From the Tools menu, choose Macro, Macros

Click on the required macro in the list, click the Edit button

or

To return to Excel:
-

From the File menu, choose Exit and Return to Microsoft Excel

Paul Watson

Excel Introduction to Macros and VBA

THE VISUAL BASIC EDITOR

Each workbook is called a Project and will appear as a bold heading in the Project
Explorer window (use the View menu if necessary to see the window).
Each project has sub sections, much like the file folders on disk, and can be
collapsed and expanded by clicking the +/- buttons.
TIP Close all windows within the VB Editor then switch back on using
the View menu. This will help you become familiar with the application.

Paul Watson

10

Excel Introduction to Macros and VBA

PROJECT EXPLORER WINDOW


Displays a hierarchical list of the projects (workbooks) and all of the items contained
in and referenced by each of the projects.

WINDOW ELEMENTS
View Code
Displays the Code window so you can write and edit code associated with the
selected item.
View Object
Displays the Object window for the selected item, an existing Document or
UserForm.
Toggle Folders
Hides and shows the object folders while still showing the individual items contained
within them.
List window
Lists all loaded projects and the items included in each project. Use +/- buttons to
show hide items.
Each item is represented by a different icon denoting its type.

PROPERTIES WINDOW
The Properties window lists the design-time properties for selected objects and their
current settings. You can change these properties at design time. When you select

Paul Watson

11

Excel Introduction to Macros and VBA

multiple controls, the Properties window contains a list of the properties common to
all the selected controls.

TO NAVIGATE THE PROPERTIES WINDOW


-

From the View menu of the Visual Basic Editor, choose Properties window
(F4)

Select the object whose properties you want to display. You can either use
the mouse to select the object or use the Project Explorer to choose from a
list

Click the Alphabetical tab to display properties in alphabetical order, or click


the Categorisation tab to display object properties by category

To change a property's value


-

Select the property in the left column

Change the property's value in the right column

Note You can enter a property's value in the right column. For those properties that
have a predefined set of values, click the value and then select one from the
values displayed in the list box.

Paul Watson

12

Excel Introduction to Macros and VBA

CODE WINDOW
Shows the code for the selected module or userform.
To view:
-

Select the module or form in the Project Window

From the View menu, choose Code

Press F7

Click the View Code button from the Project Window

Double click the module name

or

or

or

Object
Box

Procedure
s /Events

Use the Code window to write, display, and edit Visual Basic code. You can open as
many Code windows as you have modules, so you can easily view the code in
different forms or modules, and copy and paste between them.

Paul Watson

13

Excel Introduction to Macros and VBA

You can drag selected text to:


-

A different location in the current Code window

Another Code window

The Immediate and Watch windows

The Recycle Bin

WINDOW ELEMENTS
Object Box
Displays the name of the selected object. Click the arrow to the right of the list box to
display a list of all objects associated with the form.
Procedures/Events Box
Lists all the events recognised by Visual Basic for a form or control displayed in the
Object box. When you select an event, the event procedure associated with that
event name is displayed in the Code window.
If (General) is displayed in the Object box, the Procedure box lists any declarations
and all of the general procedures that have been created for the form. If you are
editing module code, the Procedure box lists all of the general procedures in the
module. In either case, the procedure you select in the Procedure box is displayed in
the Code window.
All the procedures in a module appear in a single, scrollable list that is sorted
alphabetically by name. Selecting a procedure using the drop down list boxes at the
top of the Code window moves the cursor to the first line of code in the procedure
you select.
Split Bar

split bar

Dragging this bar down, splits the Code window into two horizontal panes, each of
which scrolls separately. You can then view different parts of your code at the same
time. The information that appears in the Object box and Procedures/Events box
applies to the code in the pane that has the focus. Dragging the bar to the top or the
bottom of the window or double-clicking the bar closes a pane.
Margin Indicator Bar

Paul Watson

14

Excel Introduction to Macros and VBA

A grey area on the left side of the Code window where margin indicators are
displayed. If you click against a line of code, a breakpoint will appear, a yellow arrow
will indicate that this statement is to be executed next when in step mode.
Procedure View Icon
Bottom left in Code Window
Displays the selected procedure. Only one procedure at a time is
displayed in the Code window.
Full Module View Icon
Bottom left in Code Window
Displays the entire code in the module.
So, to view the code you have just created, follow these steps:
-

Load VB Editor (ALT F11)

Show Project Explorer window (Press CTRL R or View, Project Explorer)

Find your workbook name and click the + sign (if visible) to expand item list
within the project

Find the Modules section and click the + to see individual modules

Double click the module you want to see and the code window should load.
Use the scroll bars or the procedure box to go to the required procedure

DOCUMENTING MACRO CODE


Of course you will remember precisely what your macro does and in which order
even if you dont use it for several months! If only that were true. Yes - everyones
least favourite task is to document the procedures and statements written in the
code. It is a very necessary part of writing any procedure to add comments as

Paul Watson

15

Excel Introduction to Macros and VBA

regularly as possible - someone else may be given the task of working with your
macros after you have left your current position.
Comment lines in Visual Basic are easily spotted as they appear in a different colour
from other text (default is green) and have an apostrophe () immediately in front.
Comment lines are normally used at the top of the module to describe the macros
within and also at the top of each individual procedure. Comments may also be
added at the end of a statement.
The example below shows a macro with comments. It should be clear from those
comments just what actions the macro will take. The comments are shown in italics.
'
' EnterAndFormat Macro
' Macro recorded on 22/05/03 by Course Tutor
' which adds data and formats
'
Sub EnterAndFormat()
Range("C6").Select
'Selects firstname cell
'Enters name into active cell
ActiveCell.FormulaR1C1 = "Course Tutor"
Range("C7").Select
ActiveCell.FormulaR1C1 = "Watson"
Range("C8").Select
ActiveCell.FormulaR1C1 = "Trainer"
Range("C9").Select
ActiveCell.FormulaR1C1 = "5"
Range("C6:C9").Select
'Selects range containing entered data
Selection.Font.Bold = True
'Makes selection bold
Selection.Font.Italic = True
'Makes selection italic
Selection.Font.ColorIndex = 3
'Makes selection red
Range("C6").Select
End Sub

RECORDING EXTRA CODE WITHIN AN EXISTING MACRO


Often, you will want to add extra code to an existing macro. Either record a new
macro then cut and paste the code to the other macro or call one macro from
another (known as a Sub Routine call).

SUBSEQUENT RECORDED MACROS


After creating the first macro, Excel will store any subsequent recorded macros on
the same module sheet, directly underneath the original macro for the duration of the
file remaining open. If the file is closed then reopened, Excel will store subsequent
recorded macros on a separate module sheet.

SUB-ROUTINE CALLED FROM ANOTHER MACRO


Rather than keeping all your code in one long macro, you will find it more efficient
and easier to understand and edit if the macros are separated into smaller, more
manageable sections. You can then use a master macro that calls each of the other
Paul Watson

16

Excel Introduction to Macros and VBA

macros as a sub routine. You call a subroutine by simply typing the name of the
macro to be run. Control will pass to that macro then return to the line directly under
the sub-routine name. The following example shows the macro named ColourIt
being called from the macro called Master.

Sub Master()
Dim GetRange as Range
MsgBox This will colour your selection
set GetRange = Application.Inputbox(Please select cells to be selected, type:=8)
Range(GetRange).Select
ColourIt
End Sub
Sub ColourIt()
With Selection.Interior
.ColorIndex = 19
.Pattern = xlSolid
End With
End Sub

Note that you can write a new macro to call in several sub procedures:
Sub DoAll()
InsertDateColumn
SelectFillArea
CopyDown
End Sub

TIP You can press CTRL+space at the beginning of a line to display


the autolist. Other procedures from the current project will be listed.
Start to type the procedures name then use tab to enter the procedure
into you macro.

TROUBLESHOOTING
Hopefully your macros will be right first time. Realistically, they will need
modification and/or debugging.

GENERAL TIPS
COMMENT OUT LINES
If you think a line of code is unnecessary, do not delete it at first, just put an
apostrophe in front to turn it into a comment line then run the macro. If it still
operates correctly, remove the line of code. If an error occurs, simply remove the
apostrophe and the line will be actioned again next time the macro is run.

Paul Watson

17

Excel Introduction to Macros and VBA

THE PERSONAL MACRO WORKBOOK


The personal macro workbook (personal.xls) is stored in the XLSTART directory.
The XLSTART directory is installed under the Office directory (usually c:\Program
Files\Office\Xlstart). Any file stored here will be loaded when Excel is started. Thus,
the personal macro workbook is loaded each time you start Excel, but you cannot
see it as it is saved hidden. All the macros held within are available for running and
can be viewed through the VB Editor.
HINT Answer Yes when asked if you want to save the file when you
close Excel. You can also save the file from within the VB Editor by
selecting it in the Project Explorer and clicking the save button.

Paul Watson

18

Excel Introduction to Macros and VBA

STEPPING THROUGH A MACRO


The VB Editor has many useful tools to enable you to analyse your code whilst it is
running. You can step through the code of a macro line by line:
-

Select Tools, Macro, Macros or click the Run Macro button on the Visual
Basic toolbar

Select the name of the macro from the list and click the Step Into button

The VB Editor window appears with a yellow highlight around the name of the
procedure you selected

If necessary, Restore, Resize and Move the VB Editor Window so you can
view the results of each line of code as it is executed

Click the Step Into button on the Debug Toolbar or press F8 to


step through the lines of code one by one. The arrow and yellow
highlight will indicate which line of code is about to run

Paul Watson

19

Excel Introduction to Macros and VBA

Note: SHIFT+F8 will step over (ie run, but not step through line by line) any
called procedures
-

Click the reset button to terminate execution of the macro

Click the run button or press F5 to continue the run of the


macro without stepping

You can drag the arrow (and yellow highlight) further down the procedure to
skip lines of code during the stepping process, or up to re-execute lines

You can edit the code as you step through the macro

or

BREAK POINTS
Setting breakpoints in your code enables you to run the macro to a specific point
then step through the code from there. This is especially useful for testing part of a
procedure.
Breakpoints are highlighted in maroon (by default). The margin running down the left
side of the code window will contain a maroon point.

SETTING/REMOVING A BREAKPOINT
-

Click in the relevant line of code

Click in the grey margin on the left side of the code window or press F9 or
select Toggle Breakpoint from the Debug menu
The line becomes dark brown-red

Paul Watson

20

Excel Introduction to Macros and VBA

Note - Breakpoints are automatically cleared when a workbook is closed


Breakpoints can be set even while stepping through the code

RUN TIME ERRORS


These happen when the code is executing if the macro encounters a problem, for
example, the macro may try to select a cell while a chart is still active. A dialog box
appears offering information and several options:

Click END to stop the macro execution

Click CONTINUE (if available) to continue with the macro (VB will try to ignore
the statement causing the error)

Click DEBUG to see the code. This shows the VB Editor code window for the
errant module (which can be resized on screen enabling you to see Excel and
the code simultaneously), which allows you to step through each statement.
Use the Debug menu and the Step Into command to move through the code
(statements about to be executed are highlighted). Click the RESET button to
stop the macro

Click HELP for more information on the possible causes of the error

Paul Watson

21

Excel Introduction to Macros and VBA

SECURITY AND DIGITAL SIGNATURES


VBA, the language written when you record a macro is a very powerful programming
language. VBA has commands which can delete files from your hard disk and
events which can be triggered by opening a file. Consequently, there is the potential
for very destructive code (viruses). The security settings in XP will determine how
Excel responds when you open a file containing macros/VBA code. If the level is set
to High (the default), only digitally signed macros from trusted sources can be
enabled.

CHANGING THE LEVEL OF SECURITY


-

select Tools, Macro, Security

click the Security button on the Visual Basic Toolbar

or

If you change the level of security from High, you should make sure that you do not
open files from unknown sources!

DIGITAL SIGNATURES
A digital signature identifies the author of the macro project and says that your
macros are safe. Where used, macro files should only be signed when no further
modifications will be made to the code. Once a modification is made the files digital
signature is removed and may need to be re-signed.

Paul Watson

22

Excel Introduction to Macros and VBA

COMMERCIAL CERTIFICATION
Digital Certificates can be obtained from commercial authorities such as VeriSign.
Normally your organisation would submit an application to obtain certification. The
certificate is then installed on the computer.
INTERNAL CERTIFICATION
Organisations can act as the certification authority for their internal users.
Certificates can be issued to developers who can then sign their macro projects.
If your macros are to be used by others you should check your
organisations/departments policy with regard to digital signatures.
SIGNING A PROJECT
Once you have obtained a digital certificate and it has been installed you can sign
your projects.
-

In the VB Editor select your project in the Project Explorer

From the menu, select Tools, Digital Signature, click the Choose button

Select the certificate from the list

Click OK twice the return to the VB Editor

Paul Watson

23

Excel Introduction to Macros and VBA

WRITING CODE
TO CREATE A NEW MACRO FROM SCRATCH WITHOUT USING THE RECORDER
Once you start to become familiar with the VBA language, you can create your own
sub procedures by typing the code or copying and pasting pieces of code from other
recorded macros.
-

Position the insertion point below the end of the last macro in the module

Type in any descriptions or comments preceded by an apostrophe (one at


the beginning of each new line)

On a new line type the word Sub, followed by a space then the name of the
macro/procedure

Excel will place the parentheses after the name automatically

Press return to start a new line

Type in the code or paste it from other macros

When finished, press return to start the final line


Note:

The Editor will write End Sub automatically. Make sure that all
code you write is placed before this line.
You do not need to name the macro anywhere else as the word
Sub followed by the name will tell Excel that it is a procedure (or
Macro)

eg
Sub MsgEndOfMacro()
Beep
MsgBox "This macro has run successfully"
End Sub
Each line must be fully valid and complete. If not the Editor will turn the text red and
give the appropriate warning.
A logical line of code can be broken up into more than one physical line (for
readability) by using space underscore ( _) then pressing return (Note that the
recorder sometimes does this)
When you type code autolists appear to help you identify the correct properties,
methods, arguments and values. For example if you type the name of an object
followed by a full stop the relevant properties and methods for that object appear:

Paul Watson

24

Excel Introduction to Macros and VBA

In the above example, type Application followed by a full-stop, then type scr to give:

Then press Tab to select ScreenUpdating, type a space then = to give:

Press Tab to select the first item in the list, ie False.

This line of code is often used at the beginning of a procedure to speed up macros
by switching off the display of range and sheet selections along with other actions
that cause the screen to flicker as the procedure runs.

OTHER USEFUL TIPS WHEN WRITING/EDITING MACROS


You can use many of the shortcuts that are available in Word, for example:
Home/End
Ctrl+Home/Ctrl+End
Drag+drop
Ctrl+ Drag+drop

beginning/end of a line
beginning/end of a module
to move text
to copy text

The above are particularly useful when you select a whole line by positioning the
mouse pointer between the grey bar at the left of the code and the first character of
the line of code.
You can use the standard editing features of Cut, Copy and Paste.
The Edit menu has Find and Replace commands.

Paul Watson

25

Excel Introduction to Macros and VBA

INSERTING NEW MODULES


You can continue adding further procedures to a module. However, to help organise
your procedures you may want to add further modules (Note: you can still call
procedures from any module in the Project):
-

Select Insert, Module

Use the properties window to rename it.


FURTHER TIP
Always type code in lower case and once you have entered or edited a
line of code always move out of the line to invoke the syntax checker.
All VB words will be title cased if the words are recognised - check for
this, as you may get a run time error, rather than a syntax error, if the
words are misspelled.

Paul Watson

26

Excel Introduction to Macros and VBA

WORKING WITH CELLS AND SELECTING RANGES


This section covers the various methods of controlling and addressing ranges and
cells through VBA.
The following table shows the same action in relative and absolute code
Action
Absolute Record
Range(A2).select
Start with
A1 as
active cell
then click in
cell A2

Relative Record
ActiveCell.Offset(1,0).Range(A1).Select

Note: The Offset method moves row first then column. Positive values represent down
and right (use negatives for up and left). The Range(A1) determines the size of the
range selected.

Start in cell
A6 then
select the
range A6 to
E20

Range(A6:E20).Select

ActiveCell.Range(A1:E15).Select

Note: Can be confusing but note the reference to ActiveCell. The range indicated is
the size of the selection from the active cell.

Start in cell
A6 then
press
CTRL
DOWN

Selection.End(xlDown).Select

Selection.End(xlDown).Select

Note: Same in both cases. Just moves active cell to bottom of filled column.

Start in cell
A6 then
press
CTRL
SHIFT
DOWN

Range(Selection, Selection.End(xlDown)).Select
Note: same for both absolute and relative
Here Range uses a slightly different syntax:
Range(StartCell,EndCell)

USING NAMED CELLS


As always, this is an excellent way to keep track of the correct cells. Dont forget,
however, that cell names tend to be globally available from any sheet, so if you copy
a worksheet containing names as part of a procedure, the names may not be
correct.
Paul Watson

27

Excel Introduction to Macros and VBA

The table below shows some ways of using range names through code.
Code
Range(VAT).value = 0.175
Range(JanTotal,MarTotal).select

Range(JanTotal:MarTotal).Select

Range(ActiveCell, "JanTotal").Select

Description
Set value of cell called VAT to 17.5%
Selects the range called JanTotal AND
the range called MarTotal (excludes cells
in between same as using CTRL)
Select the range starting with JanTotal
and ending with MarTotal including the
cells in between.
Selects the inclusive range from the
active cell to the named cell JanTotal

Note: the named ranges JanTotal and MarTotal are single cells.

Paul Watson

28

Excel Introduction to Macros and VBA

PROCEDURES
A procedure is a block of code entered in a module and executed as a unit. A
procedure tells the application how to perform a specific task. All procedures must
start with their chosen procedure type (Sub or Function), then have a name followed
by a pair of brackets. A Sub routine procedure performs an action but does not
return a value. A Function procedure is similar, but it returns a value.
If the procedure is a Sub, then it does not require arguments inside the brackets
(although an argument can be used to pass a value to the procedure). A Function
would normally have the arguments to be used in the calculation inside its brackets.
Multiple arguments are separated by commas. To use a Function procedure as a
user-defined function, it cannot perform actions that change the Excel environment.

MACRO, SUB ROUTINE OR PROCEDURE?


A subroutine without an argument (or parameter) defined in the brackets is called a
Macro. These are the procedures you record and by far the most common
procedures you will write. They appear in the macro run dialog box and can be
attached to worksheet and toolbar buttons, or run with an assigned shortcut key
Subroutines with arguments are not macros and can only be run or called by other
procedures (and will not appear in the macro run dialog or be available to assign to
toolbar buttons, shortcut keys etc)
In summary: a macro is both a subroutine and procedure. A subroutine is not
necessarily a macro but is always a procedure. A function procedure is neither a
macro nor a subroutine.

Procedures
Subroutines
Macro

CALLING ANOTHER PROCEDURE


Rather than keeping all your code in one long procedure, you will find it more
efficient and easier to understand and edit the code if you separate complex code
tasks into more manageable units. You can then use a master procedure to call the
other procedures as sub-routines.

Paul Watson

29

Excel Introduction to Macros and VBA

To call another procedure, simply type its name in the code. Each time a procedure
is called, Visual Basic executes the statements between that procedures Sub and
End Sub or Function and End Function statements and then returns to the line of
code below the sub-routine name in the calling procedure.
Sub DoAll()
InsertDateColumn
SelectFillArea
CopyDown
End Sub

TIP You can press CTRL+space at the beginning of a line to display


the autolist. Other procedures from the current project will be listed.
Start to type the procedures name then use tab to enter the procedure
into you macro.

EXIT SUB AND END STATEMENTS


The Exit Sub statement immediately exits the Sub procedure in which it appears.
Execution continues with the statement following the statement that called the Sub.
The End statement terminates procedure execution.

Paul Watson

30

Excel Introduction to Macros and VBA

VARIABLES
A variable is a named storage location that can contain a certain type of data that
can be modified during program execution. Each variable has a unique name that
identifies it within its level of scope. Variable names must begin with an alphabetic
character, cannot contain an embedded period or type-declaration character, and
must be unique within the same scope.

DATA TYPES
The following table shows the supported data types, including their storage sizes and
ranges.
Data type
Byte
Boolean
Integer
Long (long integer)
Single (singleprecision floatingpoint)
Double (doubleprecision floatingpoint)

Storage size
1 byte
2 bytes
2 bytes
4 bytes
4 bytes

Currency (scaled
integer)
Date
Object

8 bytes

8 bytes

8 bytes
4 bytes

String

1 byte per
character

Variant

16 bytes + 1
byte for each
character
Number
required by
elements

User-defined (using
Type)

Paul Watson

Range
0 - 255
True or False.
-32,768 to 32,767.
-2,147,483,648 to 2,147,483,647.
-3.402823E38 to -1.401298E-45 for negative
values; 1.401298E-45 to 3.402823E38 for
positive values.
-1.79769313486232E308 to 4.94065645841247E-324 for negative values;
4.94065645841247E-324 to
1.79769313486232E308 for positive values.
-922,337,203,685,477.5808 to
922,337,203,685,477.5807.
January 1, 100 to December 31, 9999.
Any Object reference.
Note that you can also declare the specific
object type (class) instead of the more generic
object:
Dim myRange as Object or
Dim myRange as Range
0 to approximately 2 billion (approximately
65,535 for Microsoft Windows version 3.1 and
earlier).
Any numeric value up to the range of a Double
or any character text.
The range of each element is the same as the
range of its data type.

31

Excel Introduction to Macros and VBA

STATEMENTS USED TO DECLARE VARIABLES


DIM
The Dim statement is used to declare variables and allocate storage space.
Dim VariableName As Type
Variables declared with Dim at the module level are available to all procedures
within the module. At the procedure level, variables are available only within the
procedure. It is generally accepted programming practice to put the Dim statement
at the beginning of the procedure.

Sub DeclareExamples()
Dim myName As String, myDepartment as String
Dim myAge As Integer
Dim mySalary As Long
Dim myTaxPayable As Single
End Sub

If you do not specify a data type or object type, the variable is Variant by default.
When variables are initialised, a numeric variable is initialised to 0, a variable-length
string is initialised to a zero-length string, and a fixed-length string is filled with zeros.
Variant variables are initialised to Empty. A variable that refers to an object must be
assigned an existing object using the Set statement before it can be used. Until it is
assigned an object, the declared object variable has the special value Nothing, which
indicates that it does not refer to any particular instance of an object.

PUBLIC
The Public statement is used at module level to declare public variables and
allocate storage space.
Public VariableName As Type
Variables declared using the Public statement are available to all procedures in all
modules in all applications unless Option Private Module is in effect; in which case,
the variables are Public only within the project in which they reside.

Paul Watson

32

Excel Introduction to Macros and VBA

SCOPE
Scope defines the accessibility and lifetime of a variable. A Visual Basic program
has three scoping levels that determine where and when an identifier is recognised
(visible), as illustrated in the following table:
Visible in
Procedure only

Declared with
Dim or Static, declared
inside a procedure.
Module
Dim, Static, Private,
(all procedures in
declared outside all
module).
procedures (top of the
module).
Project
Public, declared outside
(all procedures in all all procedures (top of the
modules in current
module).
project, and all
referencing
projects).
If your variable names are unique within a project, you need not qualify them with the
module name. Variables defined at procedure level (within procedures) are private
to the procedure in which they are defined and are never visible outside the
procedure. Variables and objects defined at module level are visible in all procedures
within the module. Only module names and the names of referenced projects are
visible at project level.
Public identifiers are visible at project level, even though they are defined at module
level. It is important to understand that visibility extends in only one direction. That
is, Public identifiers in a directly referenced project are visible in a directly
referencing project, but identifiers in the referencing project are not visible within the
referenced project.

The list below shows which variables would be visible to the various procedures:
One()
Two()
Three()

Paul Watson

A,B,C,D,E
A,B,D,E
A,D,E,F,G

33

Excel Introduction to Macros and VBA

OPTION EXPLICIT
This statement is used at module level to force explicit declaration of all variables in
that module. It can be typed manually in a module before any statements that
declare variables or define constants. You can also turn on the Require Variable
Declaration check box in the Editor tab in the Tools, Options dialog box. Each time
you insert a new module Option Explicit will be placed automatically in the
Declarations area at the top of the module.

When you use the Option Explicit statement, you must explicitly declare all
variables. If you attempt to use an undeclared variable name, an error occurs at
compile time.

This helps you to avoid incorrectly typing the name of an existing variable or to avoid
risking confusion in code where the scope of the variable is not clear.

Paul Watson

34

Excel Introduction to Macros and VBA

CONDITIONAL TESTING
IF..THEN..ELSE STRUCTURE
The If statement conditionally executes a group of statements, depending on the
value of an expression.
Syntax 1
If condition Then statements [Else elsestatements ]
Syntax 2
If condition Then
[statements]
[ElseIf condition-n Then
[elseifstatements]] . . .
[Else
[elsestatements]]
End If
The If statement syntaxes have these named-argument parts:
Part

Description

condition

Numeric or string expression that evaluates True or False.

statements

One or more statements executed if condition is True. In


Syntax 1, multiple statements can be separated by colons.

elsestatements

One or more statements separated by colons; executed if


condition is False.

condition-n

Numeric or string expression that evaluates True or False.

elseifstatements

One or more statements executed if associated condition-n is


True.

elsestatements

One or more statements executed if no previous condition-n


expressions are True.

You can use the single-line form (Syntax 1) for short, simple tests. However, the
block form (Syntax 2) provides more structure and flexibility than the single-line form
and is usually easier to read, maintain, and debug.
When executing a block If (Syntax 2), condition is tested. If condition is True, the
statements following Then are executed. If condition is False, each ElseIf condition
(if any) is evaluated in turn. When a True condition is found, the statements
immediately following the associated Then are executed. If none of the ElseIf
conditions are True (or if there are no ElseIf clauses), the statements following Else
are executed. After executing the statements following Then or Else, execution
continues with the statement following End If.

Paul Watson

35

Excel Introduction to Macros and VBA

The Else and ElseIf clauses are both optional. You can have as many ElseIf
clauses as you want in a block If, but none can appear after an Else clause. Block If
statements can be nested; that is, contained within one another.
What follows the Then keyword is examined to determine whether or not a
statement is a block If. If anything other than a comment appears after Then on the
same line, the statement is treated as a single-line If statement.
A block If statement must be the first statement on a line. The Else, ElseIf, and End
If parts of the statement can have only a line number or line label preceding them.
The block If must end with an End If statement.

CONDITIONAL LOOPING - DO LOOP


The Do Loop statement repeats a block of statements while a condition is True or
until a condition becomes True.
Syntax 1
Do [{While | Until} condition]
[statements]
[Exit Do]
[statements]
Loop
Syntax 2
Do
[statements]
[Exit Do]
[statements]
Loop [{While | Until}condition]
The Do...Loop statement syntax has these parts:
Part

Description

condition
statements
is

Expression that is True or False.


One or more statements that are repeated while or until condition
True.

The Exit Do can only be used within a Do...Loop control structure to provide an
alternate way to exit a Do...Loop. Any number of Exit Do statements may be
placed anywhere in the Do...Loop. Often used with the evaluation of some condition
(for example, If...Then), Exit Do transfers control to the statement immediately
following the Loop. When used within nested Do...Loop statements, Exit Do
transfers control to the loop that is one nested level above the loop where it occurs.

Paul Watson

36

Excel Introduction to Macros and VBA

INPUT AND TESTING TECHNIQUES


MESSAGE BOXES
The MsgBox function displays a message in a dialog box, waits for the user to
choose a button, and returns a value indicating which button the user has chosen.

MsgBox(prompt[,buttons][,title][,helpfile,context])
The MsgBox function syntax has these named-argument parts:
Part

Description

prompt

String expression displayed as the message in the dialog box. The


maximum length of prompt is approximately 1024 characters,
depending on the width of the characters used. If prompt consists of
more than one line, be sure to include a carriage return (character
code 13) or carriage return linefeed (character code 10) between
each line.

buttons

Numeric expression that is the sum of values specifying the number


and type of buttons to display, the icon style to use, the identity of
the default button, and the modality. If omitted, the default value for
buttons is 0.

title

String expression displayed in the title bar of the dialog box. If you
omit title, nothing is placed in the title bar.

helpfile

String expression that identifies the Help file to use to provide


context-sensitive Help for the dialog box. If helpfile is provided,
context must also be provided.

context

Numeric expression that is the Help context number the Help author
assigned to the appropriate Help topic. If context is provided,
helpfile must also be provided.

The buttons named argument has these values: you can specify which buttons you
want to display by using the constant name or the value (e.g. VbYesNo is equivalent
to 4)
Constant
vbOKOnly

Paul Watson

Value
0

Description
Display OK button only.

37

Excel Introduction to Macros and VBA

Constant
vbOKCancel
vbAbortRetryIgnore
vbYesNoCancel
vbYesNo
vbRetryCancel
vbCritical
vbQuestion
vbExclamation
vbInformation
vbDefaultButton1
vbDefaultButton2
vbDefaultButton3
vbApplicationModal

Value
1
2
3
4
5
16
32
48
64
0
256
512
0

vbSystemModal

4096

Description
Display OK and Cancel buttons.
Display Abort, Retry, and Ignore buttons.
Display Yes, No, and Cancel buttons.
Display Yes and No buttons.
Display Retry and Cancel buttons.
Display Critical Message icon.
Display Warning Query icon.
Display Warning Message icon.
Display Information Message icon.
First button is default.
Second button is default.
Third button is default.
Application modal; the user must respond to
the message box before continuing work in the
current application.
System modal; all applications are suspended
until the user responds to the message box.

The first group of values (0-5) describes the number and type of buttons displayed in
the dialog box; the second group (16, 32, 48, 64) describes the icon style; the third
group (0, 256, 512) determines which button is the default, and the fourth group (0,
4096) determines the modality of the message box. When adding numbers to create
a final value for the argument buttons, use only one number from each group. The
constants mask the numbers and can also be added together. Although the code is
longer, it is clearer to read:
vbExclamation+vbYesNo+vbDefaultButton2

The constants are specified by Visual Basic. As a result, the names can be used
anywhere in your code in place of the actual values.
Return Values
When the user clicks a button, the Value shown below will be sent to the variable (if
used)
Constant
vbOK
vbCancel
vbAbort
vbRetry
vbIgnore
vbYes
vbNo

Paul Watson

Value
1
2
3
4
5
6
7

Button Selected
OK
Cancel
Abort
Retry
Ignore
Yes
No

38

Excel Introduction to Macros and VBA

EXAMPLE MESSAGE BOXES


Example 1 Simple Message Box

X = 17.5
MsgBox X

Example 2 Message box with buttons and title

MsgBox "Do you want to continue?", vbYesNo+vbQuestion, _


Title:="VBA Course"

Because no variable has been used, the macro will be unaffected whether they click
Yes or No
Example 3 Message box with buttons and title and storing return value in
variable

Response = MsgBox("Do you want to continue?", vbYesNo+vbQuestion, _


Title:="VBA Course")

The variable named Response has been used to capture the return value from the
message box. This can then be used to test (most commonly with an IF statement,
executing different code depending on a Yes or No click).

Paul Watson

39

Excel Introduction to Macros and VBA

INPUTBOXES
INPUTBOX FUNCTION
The InputBox function displays a prompt in a dialog box, waits for the user to input
text or choose a button, and returns the contents of the text box to a variable.
HINT The return is ALWAYS set to a string. Use the InputBox Method
if working with other specific data types (discussed next).

InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])
The InputBox function syntax has these named-argument parts:
Part

Description

prompt

String expression displayed as the message in the dialog box. The


maximum length of prompt is approximately 1024 characters,
depending on the width of the characters used. If prompt consists of
more than one line, be sure to include a carriage return (character
code 13), or carriage return linefeed (character code 10) between
each line.

title

String expression displayed in the title bar of the dialog box. If you
omit title, nothing is placed in the title bar.

default

String expression displayed in the text box as the default response if


no other input is provided. If you omit default, the text box is
displayed empty.

xpos

Numeric expression that specifies, in twips, the horizontal distance of


the left edge of the dialog box from the left edge of the screen. If
xpos is omitted, the dialog box is horizontally centred.

ypos

Numeric expression that specifies, in twips, the vertical distance of


the upper edge of the dialog box from the top of the screen. If ypos
is omitted, the dialog box is vertically positioned approximately onethird of the way down the screen.

helpfile

String expression that identifies the Help file to use to provide


context-sensitive Help for the dialog box. If helpfile is provided,
context must also be provided.

context

Numeric expression that is the Help context number the Help author
assigned to the appropriate Help topic. If context is provided,
helpfile must also be provided.

Paul Watson

40

Excel Introduction to Macros and VBA

When both helpfile and context are supplied, a Help button is automatically added to
the dialog box.
If the user chooses OK or presses Enter, the InputBox function returns whatever is in
the text box. If the user chooses Cancel, the function returns a zero-length string
("").
EXAMPLE INPUTBOX FUNCTION

strName = InputBox(Please Enter Your Name)

Where the variable strName will hold the name entered (if a name is entered and
the OK button is clicked, or a null string () if the CANCEL button is clicked.
TIP Always build in code for a cancellation. Generally, the best way to
do this is to use an IF statement
e.g. IF strName = Then End

Paul Watson

41

Das könnte Ihnen auch gefallen