Beruflich Dokumente
Kultur Dokumente
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
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.
From the Tools menu, choose Macro and Record New Macro...
Paul Watson
Enter a name for the macro (up to 64 characters, no spaces, starting with a
letter)
Paul Watson
Create a separate file for the code to be held in - good for building macro
library files.
-
STOP RECORDING
To stop the recorder:
-
or
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)
Paul Watson
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.
-
Paul Watson
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
Next time you point to the object, the mouse will become a pointing finger. Clicking
will run the macro.
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)
Paul Watson
To customise:
-
Still in Customise mode, click the right mouse button on the new item
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
Paul Watson
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.
-
Point to a toolbar
Select Customize (or select Tools, Customize from the main menu)
Select Assign Macro... and select the required macro from the list
Paul Watson
Click in the CTRL + box and press SHIFT plus the letter you wish to use
Paul Watson
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.
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
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
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
multiple controls, the Properties window contains a list of the properties common to
all the selected controls.
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
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
CODE WINDOW
Shows the code for the selected module or userform.
To view:
-
Press F7
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
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
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:
-
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
Paul Watson
15
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
16
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
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
Paul Watson
18
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
Paul Watson
19
Note: SHIFT+F8 will step over (ie run, but not step through line by line) any
called procedures
-
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 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
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
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
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.
-
From the menu, select Tools, Digital Signature, click the Choose button
Paul Watson
23
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
On a new line type the word Sub, followed by a space then the name of the
macro/procedure
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
In the above example, type Application followed by a full-stop, then type scr to give:
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.
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
Paul Watson
26
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)
27
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
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.
Procedures
Subroutines
Macro
Paul Watson
29
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
Paul Watson
30
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
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
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
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
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
statements
elsestatements
condition-n
elseifstatements
elsestatements
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
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.
Description
condition
statements
is
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
MsgBox(prompt[,buttons][,title][,helpfile,context])
The MsgBox function syntax has these named-argument parts:
Part
Description
prompt
buttons
title
String expression displayed in the title bar of the dialog box. If you
omit title, nothing is placed in the title bar.
helpfile
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
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
X = 17.5
MsgBox X
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
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
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
title
String expression displayed in the title bar of the dialog box. If you
omit title, nothing is placed in the title bar.
default
xpos
ypos
helpfile
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
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
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