Documente Academic
Documente Profesional
Documente Cultură
97/2000/XP
Practical workbook
Document Information
Related Documentation
Other related documents are available from the web at:
www.bristol.ac.uk/is/learning/documentation/docs-by-category.html#ss
Other books are available:
Writing Excel Macros, Steven Roman, (Excel 97 and 2000) O'Reilly http://www.oreilly.com/
Excel 97 Programming for Windows for Dummies, John Walkenbach
Excel 2000 Programming for Dummies, John Walkenbach
Excel 2002 Power Programming with VBA, John Walkenbach (Wiley and sons)
Keyboard shortcuts
The following keyboard shortcuts may be of use whilst using these notes:
<Alt><F11> To open the Visual Basic Editor (VBE) or switch between the
VBE and your workbook.
<F1> Use within the VBE window to obtain help on VB functions,
objects and properties. Click within the word you require help
with (do not select the word) and press <F1>.
<F9> Toggle breakpoints – position your cursor on a macro
statement within the Visual Basic editor and press <F9> to set
a breakpoint. When the macro is run, processing is
suspended at the breakpoint(s) to allow you to inspect
variable values and see what is going on.
<Ctrl><Shift><F9> To clear all breakpoints.
<F2> Use within the VBE window to display the Object Browser
window.
Contents
Keyboard shortcuts
Related documentation
Task 1 Virus protection ........................................................................................1
Task 2 Recording a macro ...................................................................................2
Task 3 Relative reference macros.......................................................................3
Task 4 Editing a recorded macro ........................................................................5
Task 5 Simple loop structures.............................................................................7
Task 6 Debugging a macro ..................................................................................9
Task 7 Using the Range object..........................................................................10
Task 8 Creating a function.................................................................................11
Task 9 Rearrange macro ....................................................................................12
Task 10 Yes/No inputs..........................................................................................14
Task 11 Error trapping and GoTo........................................................................15
Task 12 MsgBox: Text & numerical values ........................................................16
Task 13 Applying formats using macros............................................................17
Task 14 Text functions .........................................................................................19
Task 15 Worksheet functions in VB ....................................................................21
Task 16 InputBox ..................................................................................................22
Task 17 Creating and using a simple form.........................................................23
Appendix A Programming structure..........................................................................26
Appendix B Visual Basic objects...............................................................................32
Appendix C Declaration and scope of variables ......................................................36
Visual Basic for Excel 97/2000/XP (exlvba-t1)
Introduction
Excel is the University's recommended spreadsheet product for Windows on PCs.
This document is intended for the more experienced user of Excel who wishes to
make use of Visual Basic for Applications (VBA).
This document does not intend to teach VBA or even the concepts of object-oriented
programming. Instead the examples in this document have been devised to show
various aspects of Visual Basic for Excel. John Walkenbach's book in the "...for
Dummies" series (see Related Information) gives a good explanation of these.
When attending courses in the training rooms in the Computer Centre the working
files and solutions referred to in this document are located in the directory
C:\User\Excel. If you are working on your own system, you need to download the file:
http://www.bristol.ac.uk/is/learning/documentation/exlvba-t1/exlvba-t1.exe, copy it to
a folder on your hard disk and run it before starting these notes.
In many cases there is continuation from one example to the next. If you wish to skip
a particular exercise you will need to load the solution file to the previous example.
When working through the examples you may also like to try modifying them in order
to make them applicable to your own uses of Excel.
Prerequisites
It is essential that you have grasped the concepts of names and conditional
functions, covered in the document Further Excel XP (document excelxp-t3 - see the
Related Documentation section for the location of this document on the web). Some
experience of structured programming will be an advantage.
Acronyms
VB Visual Basic
VBA Visual Basic for Applications
VBE Visual Basic Editor
Visual Basic for Excel 97/2000/XP (exlvba-t1)
The solution files used for this practical document and the files you will create
when working through these notes will contain macros that you will wish to
run. You will therefore need to enable macros when opening them. However,
it is not a habit you should get into - always consider each file on an individual
basis and only enable macros if you believe them to be genuine. Incidentally,
a poorly written macro could also cause unintended damage, so always
check your own macros carefully before distributing them amongst
colleagues/research groups.
Enabling the Macro virus protection only offers a warning to the existence of a
macro. It does not scan the workbook for known prank macros.
Additional virus protection software is available for this purpose.
If you wish to know more about viruses and the virus protection available
within the University, please see the online information available from
http://www.bristol.ac.uk/is/computing/advice/virus/.
1
Visual Basic for Excel 97/2000/XP (exlvba-t1)
If you fail to stop recording the macro at this stage, you will create an infinite
loop of record and playback.
2.6 Select Sheet2 and cell A1.
Note If you do not have a Sheet2; from the Insert menu, select Worksheet.
2.7 From the Tools menu, select Macro and Macros.
Select Company_name, click on Run and watch the result.
2.8 Select Sheet3 and click in cell A1.
Run the macro again, this time by pressing <Ctrl>+<n>.
2.9 Insert a new Worksheet and click in a cell other than cell A1.
Run the macro again and observe where the title heading and formatting are
inserted.
2.10 Do not close the current workbook.
2
Visual Basic for Excel 97/2000/XP (exlvba-t1)
Note If the Stop Recording toolbar does not appear, first stop your macro from
recording:
- From the Tools menu, select Macro, Stop Recording.
Add the Stop Recording toolbar to the list of available options:
- From the View menu, select Toolbars, Customize.
- Select Stop Recording from the list of available toolbars and click on
Close.
You will now need to start recording your macro again from task 3.2.
3.5 Type January then copy (auto-fill) this across the row to cell L1, to get
January:December.
Change the format of the cells; for example, font, size, bold, etc.
Format these cells so that they are vertically aligned (orientation 90 degrees).
Select the columns A:L and AutoFit the column selection to make them best-
fit.
3.6 Click in cell A2 and Stop recording the macro (as in task 2.5).
3.7 Select Sheet2 and click in any cell other than A1.
Run the macro (<Ctrl>+<m>) and watch the result. Do not close the
workbook.
Note These macros have been saved in the relevant workbooks. When the
workbook is closed, any macros available within it will no longer be available
to open workbooks. If you then want to create macros available for use in all
your workbooks you will need to store them in the Personal Macro Workbook.
To do this, select Personal Macro Workbook from the Store macro in the
dropdown box of the Record Macro dialog box (in task 3.3).
3
Visual Basic for Excel 97/2000/XP (exlvba-t1)
If you want to make any changes to the macro (as in the next task) you will
first need to unhide personal.xls. From the Window menu, select Unhide and
with personal.xls highlighted, click on OK.
When you quit Excel you will be asked if you wish to save the changes made
to the personal macro workbook. If you click on Yes, the file personal.xls is
opened as a hidden workbook.
The personal.xls workbook is opened next time you start Excel and is not
available to other users.
4
Visual Basic for Excel 97/2000/XP (exlvba-t1)
4.5 From the File menu, select Close and Return to Microsoft Excel. If you
made any changes to the code, run your macro again.
4.6 Close any open Excel workbooks, discarding changes.
Note This example shows how some objects are referenced in VBA and illustrates the
WITH … END WITH programming structure. Appendices A and B define other
programming structures, common programming terms, and give more information
about Visual Basic objects. Now would be a good time to take a brief look at
these notes.
Lines that are just text comments and not Visual Basic commands are
preceded with a single quotation mark.
6
Visual Basic for Excel 97/2000/XP (exlvba-t1)
Indentation is used in the program loop above. This makes it easier to follow
the various structures within procedures. See Appendix A for a definition of
common programming terms and examples of other ways of getting code to
be repeated.
7
Visual Basic for Excel 97/2000/XP (exlvba-t1)
This example makes use of variables that we choose to call Rw and Numb.
They contain temporary values that are changed as the macro is run. We
have not specified what kind of values are to be stored in these variables. As
programming beginners this is probably the best course of action. Visual
Basic treats these variables as of type Variant and is very tolerant of the kind
of information that can be stored in them. Sometimes this tolerance can lead
to undesirable errors. See Appendix C for information on how you can specify
variables more precisely.
8
Visual Basic for Excel 97/2000/XP (exlvba-t1)
6.1 Using the macro created in the previous task, switch to the VBE (press
<Alt>+<F11>).
6.2 Alter the line Cells(Rw, "A") = Number to: Cells(Rww, "A") = Number
Re-run the macro; a runtime error message dialog box is displayed, see
Figure 2.
Click on Debug.
You should now be in the Visual Basic run-time debug mode with the line
causing the problem highlighted.
6.3 Position the mouse cursor over a variable, for example Number. Note that the
current value for the variable is displayed.
6.4 Position the cursor over the misspelt variable, Rww. The text Rww = Empty
is displayed.
6.5 Correct the mistake (remove the extra w).
6.6 From the Visual Basic Run menu, select either:
Continue to resume processing the macro, OR:
Reset and then switch to the worksheet before re-running the macro.
Note When editing a Visual Basic macro you can position the cursor on a macro
statement and set (or unset) breakpoints (from the Debug menu, select
Toggle Breakpoint or press <F9>). When the macro is next run, execution
will stop before the statement and enter into the debug mode. You can then
inspect variables and see what is going on. To restart the macro, from the
Run menu, select Continue. To clear all breakpoints, from the Debug menu,
select Clear All breakpoints (or press <Ctrl>+<Shift>+<F9>).
9
Visual Basic for Excel 97/2000/XP (exlvba-t1)
Cells can have their format attributes set directly. For example,
Range(“A1:A100”).Font.Name = “Arial”
Quite often it is convenient to use the With… End With language construct
so that the attributes of a range of cells can be set without repeating the
range specification each time. NB References to objects within the construct
that begin with “.” are assumed to have the With object as their parent
object.
7.3 Switch to the spreadsheet, delete the contents and run the myloop macro.
Note the effect of the formatting on the cells.
7.4 Close your workbook. There is no need to save it.
10
Visual Basic for Excel 97/2000/XP (exlvba-t1)
11
Visual Basic for Excel 97/2000/XP (exlvba-t1)
This task assumes a working knowledge of cell and range names (covered in
document exl00-t3).
9.1 Open the file Exam1.xls (in Computer Centre training rooms, this is in the
folder C:\User\Excel). The worksheet contains some subject results for
fictional students (Figure 3).
This task will rotate those results (Figure 4) in order to make use of other
features within Excel such as Subtotals and PivotTables.
9.2 Highlight the range A1:G13 and define a range name, area.
Click in cell I1 and define a name, areaoutstart.
9.3 Switch to the VBE and insert a new module.
Insert a new procedure (subroutine) named rearrange.
12
Visual Basic for Excel 97/2000/XP (exlvba-t1)
For programming flexibility we make use of variables (in this case ar and
arout) to point at the input and output ranges. Such variables must be
assigned values using the Set command rather then just using the “=”
assignment statement.
Without any leading range qualifier, cells references all the cells within the
currently active worksheet. But with a leading range object it is made to
reference the cells relative to that particular range. For example,
ar.cells(1,1), references the first cell in whatever range that ar points at.
9.5 Switch back to the worksheet (click on the icon in the Status bar or use
<Alt><F11>).
9.6 Save your workbook.
9.7 From the Tools menu, select Macro/Macros and with the rearrange macro
selected, click on Run.
13
Visual Basic for Excel 97/2000/XP (exlvba-t1)
The ampersand character, &, is used to string together text strings and text
variables whilst the underscore character, _, allows you to continue a single
line command on the following line for display purposes. Blank spaces are
ignored. Indentation in an application is used to make the program easier to
read and debug.
The standard constant vbCr is used to insert a carriage return into your
dialog box.
The standard constant vbYes is returned if the Yes button is clicked in reply
to the message.
14
Visual Basic for Excel 97/2000/XP (exlvba-t1)
11.1 Using the macro created in the previous task switch to the VBE.
If you have not successfully completed the previous task, you will need to
open the solution file, vbexam_b.xls, before starting.
11.2 Immediately beneath the line macroname = “rearrange”, insert a new line
and type: On Error GoTo errmsg
If the ranges area and areaoutstart have not been defined in your
spreadsheet, the macro will jump to a point labelled errmsg (defined below in
task 11.4).
11.3 Beneath the lines set ar… and set arout… add the command
On Error GoTo 0. This section of code should now resemble:
On Error GoTo errmsg
Set ar = Range("area")
Set arout = Range("areaoutstart")
On Error GoTo 0
Any errors encountered from this point on in your macro will display the
normal system errors rather than the one you specify in the errmsg section.
11.4 Scroll to the end of the macro and add an errmsg section immediately above
the last (End Sub) line:
errmsg:
MsgBox "Bad input/output range.", vbOKOnly
End Sub
11.5 Immediately above the errmsg: line, add a new line Exit Sub to ensure that
this error message is only reached from the GoTo command entered in task
11.2.
11.6 Switch to the spreadsheet and save your workbook.
11.7 Delete your previous output and check that the macro runs without error.
Try deleting one or both of the range names (from the Insert menu, select
Name / Define) and test the macro again.
Note You may also wish to check that the selected input range ar is sufficiently big
and that the output range areaoutstart is not within the input range, area.
Your macro should then exit after displaying a dialog box.
15
Visual Basic for Excel 97/2000/XP (exlvba-t1)
12.1 If you have not completed the previous tasks, first open vbexam_c.xls.
12.2 Switch to the VBE and scroll to the foot of your macro.
12.3 Between the lines Next r and Exit Sub, add the following code:
If aroutr > 1 Then
arout.Cells(aroutr - 1, 3).Select
MsgBox "This macro has output " & _
Str(aroutr - 2) & " lines." & vbCr & _
"It found " & Str(countblankcells) & _
" blank cells.", vbOKOnly, macroname
Else
MsgBox "No lines output!", vbYesNo, macroname
End If
12.4 From the File menu (still within the VBE), select Close and Return to
Microsoft Excel.
12.5 Save your workbook and test the macro.
Note Vbexam_d.xls contains a working solution to this exercise.
12.6 Close any open workbooks. There is no need to save changes.
16
Visual Basic for Excel 97/2000/XP (exlvba-t1)
13.1 Open the file created in task 8 (Creating a function) and press <Alt>+<F11>
to switch to the VBE.
Insert a new Procedure, named RemoveSign (type = Sub,
Scope = Public).
13.2 We first need to select the last cell in use within the active worksheet. Enter
the following code into your procedure:
ActiveSheet.Cells.SpecialCells(xlLastCell).Select
ir = ActiveCell.Row
ic = ActiveCell.Column
For rw = 1 To ir
For col = 1 To ic
If IsNumeric(Cells(rw, col)) And Not _
IsEmpty(Cells(rw, col)) Then
in_no = Cells(rw, col)
If Cells(rw, col).NumberFormat = "0.00%" Then
Cells(rw, col) = times100(in_no)
Cells(rw, col).NumberFormat = "General"
End If
End If
Next col
Next rw
Note Working through this code from top to bottom:
The last cell in the worksheet is located and the variables ir and ic are set to
the row and column position values of that cell.
The For Rw… and For Col… structures ensure that the procedure loops
through each row and column used in the worksheet.
The first If… End If structure checks to see if the current cell is not empty and
that its value is numerical. If these conditions are not met, the procedure
moves to the next column/row. If the conditions are met, the variable in_no is
set to the value of the current cell and the next If…End If statement looks to
see if the current value is formatted as a percentage with 2 decimal places. If
it is, the value is multiplied by 100 (using the function created in task 8) and a
general format applied.
13.3 Switch to the worksheet view, save your file and enter some values in your
worksheet (ensuring you have one or more numeric values formatted as
percentages with 2 decimal places).
13.4 Test your VBA (vbformat.xls contains a working solution with some sample
values to test it on).
13.5 The second If…End If statement in the above code could be extended to deal
with Percentage formats with different numbers of decimal places (see the
commented out section of vbformat.xls).
17
Visual Basic for Excel 97/2000/XP (exlvba-t1)
18
Visual Basic for Excel 97/2000/XP (exlvba-t1)
19
Visual Basic for Excel 97/2000/XP (exlvba-t1)
14.11 Select columns B:D and from the Format menu, select Column/Hide.
Note See vbreverse_a.xls for a working solution.
20
Visual Basic for Excel 97/2000/XP (exlvba-t1)
15.1 If you completed the previous task, unhide columns B:D and delete the
formulae in the range B2:E5.
Otherwise enter the text as described in tasks 14.1 to 14.3 above.
15.2 Switch to the VBE.
15.3 Create the following VB function:
Function getSurname(t)
backText = rev(t)
spaceLoc = Application.WorksheetFunction. _
Find(" ", backText)
backSurname = Left(backText, spaceLoc - 1)
getSurname = rev(backSurname)
End Function
15.4 Switch to the worksheet and click in cell B2.
Enter the formula =getSurname(A2).
15.5 Copy (drag & fill) this formula into the range B3:B5.
Note The file vbreverse_a.xls contains a working solution.
There is a Visual Basic function called InStr that does the same job as the
Excel Find function and would be more efficient to use. This task simply
demonstrates the use of an Excel worksheet function within a Visual Basic
macro.
21
Visual Basic for Excel 97/2000/XP (exlvba-t1)
Task 16 InputBox
Objectives To obtain and use input from the user.
Comments You must first have successfully completed task 15.
16.1 With the worksheet created in task 15 open, switch to the VBE.
16.2 From the Insert menu, select Procedure.
16.3 Type the name Surname and click on OK.
16.4 Complete the procedure as shown in bold:
Public Sub Surname()
myString = InputBox("What is the full name?")
Msg = "The surname is "
MsgBox Msg & getSurname(myString), vbOKOnly
End Sub
16.5 Run the procedure (press <F5> or from the Visual Basic Run menu, select
Run Sub/UserForm).
16.6 When prompted, enter the name Dr P A Brown and click on OK.
Note See vbreverse_b.xls for a working solution together with additional code for
allowing the user to select the Cancel button (or press the <Esc> key). The
solution also deals with blank and numeric values entered into the dialog box.
Using forms to obtain and display info.
22
Visual Basic for Excel 97/2000/XP (exlvba-t1)
If you ever “lose” the Toolbox window you can use the View / Toolbox VBE
menu command to show it again.
17.6 Right click on any of the controls in the form and select Properties from the
drop down list.
Note A list of all the properties that control the behaviour and look of the selected
control is shown. Note that there is a (name) property for each control - this is
used to identify the control in VB code. It and the other properties can be
altered either via the properties window or in VB code. Do not alter any of the
properties now.
17.7 Double click on UserForm1 in the Project Explorer window to re-show the
form currently being designed.
17.8 Right click on the CommandButton1 control in the form design window and
select View Code from the drop down list.
Note A window displaying the code that will be obeyed when the control gets
clicked is displayed. Initially this code is:
End Sub
23
Visual Basic for Excel 97/2000/XP (exlvba-t1)
17.9 Insert the following line before the End Sub line:
24
Visual Basic for Excel 97/2000/XP (exlvba-t1)
using the VBE Tools References and Additional Controls menus as outlined
above.
25
Visual Basic for Excel 97/2000/XP (exlvba-t1)
For our purposes you can regard a program (or macro) as a number of statements that are
interpreted by the computer according to a set of syntactic rules.
Each set of rules correspond to a particular language – for instance there are languages
called FORTRAN and VISUAL C.
The language that is used in the Excel environment to provide macros is called VISUAL
BASIC FOR EXCEL.
This language is used with slight differences for many other Office applications e g there is
VISUAL BASIC FOR WORD.
These are all grouped together as a product called VISUAL BASIC FOR APPLICATIONS (or
VBA for short). The facilities available are identical except for the objects that are made
available for manipulation. For instance, by default, the ACTIVECELL object would be
available in Excel but not in Word.
They share a common editor (VBE for short) and navigation window environment (called the
PROJECT EXPLORER).
(There is also a stand alone product called just VISUAL BASIC which can be used to create
stand alone executable programs and does not need an Office product to be running – but
this course is not concerned with this).
Before you can start typing new macros or changing old ones you must go to the Visual
Basic Editor (VBE) window, use the PROJECT EXPLORER window to select the project (i.e.
the workbook your macros are associated with), and then either insert a new module or
double click on an existing module - the statements associated with the module will then be
shown in a separate window.
Modules are attached to particular workbooks and used to store macros. There can be more
then one module in a workbook and each module can hold many macros. A Macro will
consist of one or more PROCEDURES.
The statements themselves are case independent (but sometimes when you enter the
statements into the VB editor it itself changes the case to get a consistent appearance).
In general the amount of spacing between the words used in the language is left up to you
(but you are advised to indent lines with leading spaces to improve the visual presentation of
the program).
Scope of procedures
Functions can be called (executed) from other VB subroutines or functions, or by a call via
the contents of an Excel cell. Subroutines can be called from other subroutines or functions
or via the Excel Tools Macro menu or via the VBE Run menu.
If their scope is Public then the item can be called from any module in the workbook or from
the Excel Tools Macro menu (if a Subroutine) or Excel cell (if a Function). If their scope is
Private then the item can only be called from the module in which the item is defined. By
default the scope is set to Public. Scope can be specifically set by preceding the Sub or
Function definition by the desired scope.
Example Public Function my_calc()
Forms
Besides procedures, VBE can also be used to create forms. These are special windows
(known as custom dialog boxes) that contain a mixture of text and special controls (such as
command buttons, pull down lists etc). These controls can be selected from a special toolbar
called a toolbox and positioned in the window. VB code can be associated with the controls
such that clicking on a control can start off programming activity. A separate course
document called VB Excel 97/2000: Custom dialog boxes (document exlvba-t2 – see
Related Documentation section for the location of this document on the web) is available that
deals with this. Before moving on to this subject you are advised to finish the current course
document.
Comments
It is a good idea to include informative non-executable comments into a program. Any line or
part of a line that begins with the ‘ character is ignored by VB language interpreter.
Example ‘ Putting comments in a program is good practice
Continuation
Sometimes it is convenient to split a single statement over more then one line. To do this the
underscore character preceded by at least one space character is used.
Example Sub _
My_Program()
Constants
Fixed values such as say 12 or TRUE or "THIS IS AN ERROR"
Variables
A named item that can contain some information. There are some rules to the names you
can choose. (No spaces are allowed). For clarity avoid the use of special programming
words such as “if” and special Excel words such as “range” or “cells”.
Declarations
Optionally (in VB) you can list the variable (and its type) before its use, using declaration
statements.
Example dim i as integer
Types of variable
Variables can hold various types of information e.g.
Boolean, Integer, Long (long integer), Single (single-precision floating-point), Double
(double-precision floating-point), Currency, Date, String or Variant.
If you do not specifically declare the type of a variable it will be given the Variant type. VB is
very flexible when dealing with variant variables.
Expressions
A mixture of constants, variables and operators that produce a value as their result.
Example x+1
(x+y)/3 +4*z
Objects
Variables can also be "objects" such as Excel workbooks, worksheets, cell address ranges,
type of fonts, charts etc.
Objects have a position in a hierarchy. For example, the Range object is below the
Worksheet object which is below the Workbook object. The VB help system will show this
relationship.
Visual Basic for Excel 97/2000 (exlvba-t1) 28
Visual Basic for Excel 97/2000/XP (exlvba-t1)
Often when referring to objects they will be defined by listing the parent object first and then
the object itself e.g.
Example Worksheets("Sheet1").Range("A1")
A period is used as the separator between objects.
Often if a parent object is not specified a default object will be assumed to be the parent. For
example, the Activesheet object is assumed if a Range object is not qualified by a parent
object.
Testing variables
You can use the IF .. THEN construct or IF .. THEN ... ELSE constructs to do this.
Example If x=1 then y=1
If ans="YES" Then test="TEST ONE" Else test= "TEST TWO"
You can also use a multi-line IF ... THEN … [ELSE …] ENDIF construct to do testing.
Example If ans="YES" Then
test="TEST ONE"
x=1
Else
test= "TEST TWO"
x=2
Endif
Looping
Various constructs enable you to get a set of instructions performed many times. For
example, the FOR... NEXT construct does this. The complete program that follows
illustrates this:
Example Sub SumCol()
colnum = 2
startrownum = 10
endrownum= 20
sumct = 0
For rownum= startrownum To endrownum
' we now use the CELLS property of the RANGE object to get the value of
‘ a particular cell, and then add it the current value of sumct and store the
‘ new total back into sumct overwriting what was there previously.
sumct = sumct + Range("A1").Cells(rownum, colnum)
If sumct > 5000000 Then Exit For
Next
' sumct will now have the sum of column 2 for rows 10 to 20.
' - Unless of course the sum was greater then 5000000 when
' it will contain whatever sum forced the exit statement from the loop.
MsgBox Str(sumct)
' MsgBox is a standard instruction that will output information to the screen.
' Str is a standard function that takes an argument of type numeric and
‘ converts it to type text , suitable for display purposes.
End Sub
Libraries
Objects are grouped in classes (for example, Excel, Office) and their
definitions stored in specific libraries. Visual Basic for Excel starts with a
default set of libraries. Libraries can easily be added to the set (from the VBE
Tools menu, select References). A reference to an object that is not in the
current set of object definitions will cause an error.
Object hierarchy
Objects have a position in a hierarchy. For example the Range object is below
the Worksheet object which is below the Workbook object. The VB help
system will show this relationship.
Often when referring to objects they will be defined by listing the parent object
first and then the object itself e.g
Example Worksheets("Sheet1").Range("A1")
A period is used as the separator character in the hierarchy.
Often if a parent object is not specified a default object will be assumed to be
the parent. For example the Activesheet object is assumed if a Range object
is not qualified by a parent object.
As can be seen from these examples, each property and method has its own
set of rules defining what arguments are necessary to construct a valid
reference to it.
If present, the arguments are enclosed in parenthesis and separated by
commas. Any text constant argument must be enclosed in double quotes.
There is an alternative form of specifying arguments using keywords that is
useful when there are many arguments.
Example Workbooks.Open Filename:="C:\Sales.xls", ReadOnly:=True
Collection objects
There are many objects that are used to control collections of objects of the
same type. For instance the Workbooks object can be used to control all the
Workbook objects. It can be used to create a Workbook, provide the names
of all the Workbook objects, a count of the Workbook objects, etc.
In general the collection objects will share many methods and properties, for
example, Count, Add, Item, Close.
From the VBE View menu, select Object Browser (or press <F2>).
From the Project/Library dropdown box, select Excel (default <All
Libraries>).
Under classes, select a class, (Range in Figure 5).
Right-click the mouse and select Help.
A separate help window will be created (if it does not already exist) containing
information about the chosen item. Quite often there will be Properties and
Methods buttons that can be clicked to get information about all the
properties and methods for the chosen object.
Note Workbooks are only differentiated by their filename (including their suffix but
not including their folder name) and names of sheets, folders and files are not
case-dependent.
If the workbook is not already open, then the macro will have to open it using
the Workbooks Open method:
Example Workbooks.Open ("C:\Ex\Large.xls")
A particular workbook may be made the active workbook via:
Visual Basic for Excel 97/2000 (exlvba-t1) 34
Visual Basic for Excel 97/2000/XP (exlvba-t1)
Example Workbook(“exone.xls”).Activate
A particular sheet may be made the active sheet via:
Example Sheets(“Sheet2”).Activate
Warning! Before the ActiveCell object can be used or a particular range selected using
the Select method, then an ActiveSheet object must have been defined.
Note Object variables point to the object rather than are the object.
It is good practice to free such variables when they are no longer required. To
do this set them to the special Nothing keyword.
Example Set Rngx = Nothing
Many objects have a default property or method that is used when the object
has not been fully specified. For a Range variable this property is normally the
Value property.
Example The statement Range(“A1”)=Range(“B1”) will be treated as
Range(“A1”).Value = Range(“B1”).Value
By assigning the data type to each variable the program will run faster and
use memory more efficiently.
Module only
If a variable is to be used throughout the procedures within a module, use a
Dim statement before the first Sub or Function statement in that module.
Example Dim First As String
Dim InterestRate As Single
Sub FirstSub()
[Write the VB code here]
End Sub
[More functions/subs here]
In the examples within this document, only a few procedures are used.
However, as a large program is developed using multiple procedures across
several modules, it becomes essential to declare all variables used.
Efficiency aside, spelling mistakes can occur within variable names leading to
incorrect calculations.
Use the statement Option Explicit as the first line within a module to force
the declaration of variables. The program will stop if a variable name has not
been declared.
Note The VBE can be configured to automatically insert the Option Explicit line in
new modules. From the Tools menu, select Options. Within the Editor tab,
select Require Variable Declaration.
See the online help facility for more information on declaring variables and
variable types.