Defiitive Guide To Excel Training

Download as pdf or txt
Download as pdf or txt
You are on page 1of 936

Definitive Guide to Excel VBA, Second Edition

MICHAEL KOFLER TRANSLATED BY DAVID KRAMER

Definitive Guide to Excel VBA, Second Edition Copyright 2003 by Michael Kofler

5.8 Protection Mechanisms ..........................................................................317

Restricting the Field of Action .......................................................................318 Protecting Cells and Worksheets from Changes ..........................................319 Protection Mechanism for Shared Workbooks ............................................324 Protecting Program Code and ToolBars .......................................................324 Syntax Summary .............................................................................................326 5.9 Configuration reting O PO5.7(kpions) Files, withProgram Custom Code Configuration ]TJ/F9 1 Tf176.355 ..............................327 0 TD(........................................... Options ............................................................................................................m27

13.3 Programming Techniques

Preface
EXCEL OFFERS RIGHT OUT OF THE BOX an enormous variety of functions. So why does

The Idea Behind This Book

Part One

An Intuitive Approach

C HAPTER 1

Writing Your First Macro


I

1.1 Definition of Terms


Macros
This chapter is entitled Writing Your First Macro. It thus seems appropriate at this point to explain the term macro. A macro is a sequence of instructions to the computer that the computer then carries out when ordered to do so.

Our next example displays a group of selected cells in a larger font size (first as an Excel 4 macro, then in VBA):
=FONT.PROPERTIES(,,GET.CELL(19)+2) Selection.Font.Size = Selection.Font.Size + 2 'Excel 4 'VBA

When the term macro is used in books or in on-line documentation it is not always made clear whether the XLM or VBA language is meant. In this book, however, the term macro will always mean a VBA macro.

NOTE

XLM made it possible to alter menus and to define custom forms. The fact that

1.3 Linking a Custom Style with a Tool

In the dialog page GENERAL deactivate COMPILE ON DEMAND (see Section 3.2).

Preparatory Tasks
Excel can distinguish in macro recording between absolute and relative movement between cells: Absolute recording is the default mode. When you move the cell pointer during recording from B2 to D4, say, the resulting command is Range(D4).Select. In relative mode, however, the command would be ActiveCell.Offset(2, 2).Range(A1).Select: Here ActiveCell.Offset(2,2) denotes the cell two rows beneath and two columns to the right of the currently active cell, while Range(A1)

Step 1: Preparing the Database, Arranging Windows


The construction of this application begins with the input of data on several books and constructing a table along the lines of Figure 1-7. This has nothing much to do with macro programming. It is merely a matter of constructing a normal Excel table. For now you should ignore the buttons and filter arrows. (If you prefer, you could just as well create an address database, an index of students, or something else entirely. You do not need to adhere precisely to our presentation. The more creatively and independently you work, the more you will learn.) Some suggestions for formatting the table: All cells of the table have been formatted with the text aligned vertically at the top of the cell (FORMAT|CELLS|ALIGNMENT). The cells in the title column have been given the attribute wrap text so that longer titles will automatically be displayed over several lines. The top two rows have had their height significantly enlarged. The entire second line has been

To add buttons you activate the control toolbox. (The control toolbox is

Figure 1-8. The control toolbox (left); the table window (middle); the properties window with settings for the selected button (right)

Now the buttons have to be linked to the program code. A double click on the button takes you to a template in the module Sheet1 for an event procedure that will be automatically executed when the button is pressed. The name of the procedure is a combination of the control name (such as btnSortAuthor) and the event (usually Click).
' books.xls, Module "Table1" Private Sub btnSortAuthor_Click() End Sub

The program code is recorded as in the previous examples. You then move the resulting instructions with Copy and Paste from the 0.0t79.6(dhe moduined to the)]TJ9 -1.0047 -1

Figure 1-9. Interest on monthly deposits

From these data three results will be computed: the date of the last deposit (n years minus 1 month after the first deposit), the end of the savings time (1 month thereafter), and the monthly rate of interest. The determination of the date demonstrates the use of the DATE function, by which a valid date is created from the data

E10 (last deposit): =DATE(YEAR(E7)+E8, MONTH(E7)-1, DAY(E7)) E11 (end of account): =DATE(YEAR(E7)+E8, MONTH(E7), DAY(E7)) E12 (monthly interest rate): =E5/12 E15 (effective annual interest rate): =(1+E12)^12-1

This macro has the distinguishing feature, among others, that it cannot be created with the macro recorderthere are no comparable functions in Excel. The

languages were German and Swedish. Apologies to all you Swedes out there!) Columns C, D, E, and F indicate whether the word in one or the other direction

Constructing the Form

NOTE Almost all of the program code for this example is connected with the form (dialog) shown in Figure 1-12. The greatest hurdle to be jumped consists in constructing this form. If you have never worked with the form editor, you should perhaps take a peek at Chapter 7 in order to understand more fully the relatively brief discussion given here.

For each of the seven controls you must set, as you did previously for the form, the Name and Caption properties. In our example program we have made the following settings:

' Example file Vocabulary.xls Option Explicit Dim firstline& Dim lastline& Dim linenr& Dim querymode& Dim excelWindowstate& Dim startcell As Range Const maxTries = 20 'first line with words 'last line with words 'current line in word table ' ' 0: lang. 1 > lang. 2, 1: lang. 2 > lang. 1

'current window state of Excel 'current cell when trainer is started 'number of tries to find a yet untrained wordocedure serForm_Initializem

If after

' vocabulary list should be corrected Private Sub btnEdit_Click() Worksheets(1).Activate startcell.Offset(linenr).Activate Unload Me End Sub ' Terminate form, save table Private Sub btnEnd_Click() Dim result& Unload Me result = MsgBox("Should the vocabulary list be saved?", _ vbYesNo) If result = vbYes Then ActiveWorkbook.Save End Sub

Additional Code
In order to get the form started correctly, a button (btnStartTrainer) is inserted i r s d M (

1.10 Example Programs for You to Try


This section gives a brief description of the most interesting examples in this book. The figures should serve as invitations to you to go ahead and fire them up and try them out. At the same time, this section should give some indication as to just

Chapter 1

Figure 1-17. An intelligent form

Automated Data Presentation with Graphs


The extensive possibilities for creating graphs and charts in Excel are often used for presenting large quantities of data in graphic format. This process lends itself, of course, to automation. In 10\Chart.xls is demonstrated how (using simulated test data) daily and monthly records of data can be created.

Figure 1-18: An automated chart


42

C HAPTER 2

Whats New in Excel 2000


T

New and Changed Objects, Properties, and Methods


Automatic backups: Excel 2002 can finally do what Word has always been able to do, namely, on a regular schedule (such as every ten minutes) make a backup copy of the current file. You can control this function in VBA code using the new AutoRecover object. One can interpret this new feature as a possible admission by Microsoft that Excel is perhaps not quite so robust as it ought to be. Worksheet protection: In Excel 2002 it is possible to protect cells so that their content cannot be changed, but the formatting, sorting, and other details are under the control of the user. For management of this new protection option the Protect method of the Worksheet object has been expanded. Furthermore, the new Protection object provides information about the current protection options. Also new is the possibility of giving individual users (with or without a password) access to selected groups of cells within a protected worksheet. This is practical when several users are allowed to access the same worksheet, but not every one of those users is permitted to make changes. Management of these settings is provided by the new objects AllowEditRange[s] and UserAccess[List].

XML: Microsoft advertises Excel 2002 as XML compatible. (XML stands for Extensible Markup Language and is a text format for representing hierarchical data.) However, the only XML function in Excel consists in allowing you to save Excel workbooks in a special XML format. The practical significance of this format is at present zero: As of yet there are no other programs that can use this format.

Neither VBA code nor embedded objects or charts can be stored in XMLfiles9.7(6()]TJT*-947

New and Changed Objects, Properties, and Methods


Directories: The new property

Importing Text: A frequent source of aggravation with previous versions of Excel was the attempt to automate the importation of ASCII files. Fortunately, there is progress to be reported. Finally, the decimal point and the thousands separator (for separating groups of three digits in the representation of numbers) can be controlled by additional parameters of the method OpenText. For importing text the revised QueryTable object can be used. Configuration Files: The locations of configuration files have changed againas has been the case with all previous versions. Everyones favorite game is Look for me! Help System: The entire help system has been completely revised and is now

The Development Environment

With the Validation object one can define validation controls for the input in cells. For example, input can be restricted to a particular format (e.g., date) or to within a range of values. Such rules can be formulated manually with D

A host of new formatting possibilities come from new properties of the Range object. IndentLevel sets how far the content of a cell is to be indented. (The permissible range is from 0 to 15.) With Borders it is now also possible to draw diagonal lines through a cell (previously, a cell could only be framed). With Orientation the text can be oriented between 90 and 90 degrees (previously, only multiples of 90 degrees were possible). The Orientation property can also be changed for many other objects, such as labels on charts.

Object Libraries
Menus/Toolbars (Office Library): You have no doubt noticed that the appearance of menus and toolbars has changed. The consequence for programmers

2.4 New in Excel 7


Since version 7 the mechanism of ActiveX automation (which at the time was called object automation) has been used to incorporate various extensions into Excel. The extensions described in this section must be activated before use with Tools|References. Furthermore, an entire library of new objects, methods, and properties is available, which can be used as Excel keywords in VBA code. Office Library: To simplify and standardize the search for Office documents,

in its own particular location. Therefore, changes made to the file are no longer global for all Excel users. In principle, this is a positiy-m development, butthe fosisi-]TJ0T*-0.000

When a worksheet is accessed, many methods function only with Worksheets(n), but not with Sheets(n) (even if in both cases the same

Part Two

Fundamentals

C HAPTER 3

References: So long as you use only the standard Excel objects, you do not need to worry about references. However, as soon as you wish to use objects

Instead of employing TOOLS|MACRO|VISUAL BASIC EDITOR or Alt+F11, the change from Excel to the development environment can be effected by means of a tool: In Excel (not in the development environment) VIEW|TOOLBARS|CUSTOMIZE|COMMANDS and with the mouse drag the button VISUAL BBBB

Project Explorer
The project window (VIEW 8.88181717 612.8123 Tm1550217(|P)Tj

Normally, the browser displays only officially supported keywords. How-

General Options
COLLAPSE PROJECT HIDES WINDOWS (tab GENERAL

Project Properties
With TOOLS|VBAPROJECT PROPERTIES (PROJECT PROPERTIES) you open a dialog for setting properties of the current project. On the page with the tab GENERAL

3.3 Code Input in Modules


VBA code can be input into any code window. As mentioned in the preceding section, there are numerous objects that can be fitted out with code: the Excel file as a whole (module Sheet 2, etc.), forms, normal modules, and class modules. While the objects and

Ctrl+ and Ctrl + Page Up, CTRL + and Ctrl+ Page Down,

Commentary
The apostrophe ( ) is used to introduce a comment. Comments are allowed both

With the command VIEW|TOOLBARS|CUSTOMIZE|COMMANDS (still in Excel) you can insert the menu entry Custom Menu Item or Custom Button (both

The macro recording is terminated with TOOLS|MACRO

CHANGING THE ACTIVE WINDOW

Alt+F11 Ctrl+Tab

switches between Excel and the development environment

C HAPTER 4

VBA Concepts
THIS CHAPTER DESCRIBES

NOTE

When you activate the option

With the keywords DefBool, DefCur, DefDbl, DefDate, DefInt, DefLng, DefObj, DefSng, DefStr, and DefVar the default data type for variables with certain initial letters can be preset. The commands must be given at the beginning of a module

Fields
Fields are lists of variables of the same name that are referenced by one or more index values. Fields are always used when several similar pieces of information (for example, the entries in a matrix) are to be manipulated.

Dimensioning Fields
Before a field can be used, it has to be defined. For this the command Dim is used, where after the field name the greatest permitted index is given in parentheses. The data type of the field is given as in the case of variables with a label or with the keyword As.

NOTE In the case of large fields you should think carefully about which data type is required. When you give no data type, VBA automatically selectsipoEfa(foe onr1.89 ) = 10:) A5) = a(4)/2poEfated imuhmolieel orn as iningrd m

O8grmation, unl, ay

This defines a field with 11 times 21 elements. With multidimensional fields,

NOTE It is not always quite clear when a data field is supported and when it is not. If you were to replace [a1:d1] by [a1:a4] in the previous example, that is, to change four adjacent cells, the definition would no longer function! The correct instruction would now be as follows:
Sheets(Table1).[a1:a4] = _ Array(Array(abc), Array(def), Array(1), Array(4))

4.2 Procedural Programming


Procedural programming languages are distinguished by the fact that program code is written in small, separate units. These program units (procedures) can be called by one another, and parameters can be passed between them. Almost all of the currently popular programming languages, such as Pascal, C, and modern dialects of Basic, belong to the family of procedural programming languages (unlike, say, the languages LISP and Prolog). This section describes the characteristic commands of a procedural language for controlling the execution of a program and for the division of the program into functions and procedures.

Procedures and Parameters


The two general syntax variants for procedures have already been revealed in the previous examples: Sub name() End Sub defines a subprogram

Function func(a As Double, b As Double) As Double If a > b Then func = a - b: Exit Function func = a * b End Function

The function func can also be used in worksheets: Input arbitrary values into A1 and B1, and in C1 place the formula =func(A1,B1). You will see that the function thus defined is executed without further ado. (Note that in worksheet formulas,

The Data Type of the Value Returned by the Function

Sub array_macro2(x%, y%) x = x * 2 y = y / 2 End Sub

After array_macro1 has finished executing, the values 8 and 3 have been output to the direct window. Thus array_macro2 has altered the values of the two variables a and b from array_macro1

arraytest_continue: dimensions = i - 1 Debug.Print dimensions, " Dimensions" For i = 1 To dimensions Debug.Print "Dimension "; i; ": "; LBound(arr, i); Debug.Print " to "; UBound(arr, i) Next i Exit Sub arraytest_error: ' this code is executed as soon as the program tries to access a nonexistent ' dimension Resume arraytest_continue End Sub

The following output is produced in the immediate window by array_macro4:


0 3 Dimension Dimension Dimension 2 Dimension Dimension 2 : 1 : 2 : 3 : dimensions dimensions 0 0 0 to to to to to 4 5 6 2 4

dimensions 1 : -2 1

Matrices as Parameters
Excel matrices can be passed as parameters to procedures. Matrices are linked regions of cells in Excel worksheets. Excel has its own worksheet functions, such as LINEST, that return not a single value, but a matrix containing several values. See also Chapter 5, where the use of the function LINEST and the programming of custom matrix functions are described. Excel automatically converts matrices into one- or two-dimensional fields.

Tht e0 73-738 r0 73wing example sh3ws a function that returns tht 9.5 1umber of mat9(n8(ix ele-

Variable Number of Parameters

Although it is nowhere documented, there is also the possibility of combining

VBA Concepts

The execution of the program for calculating the factorial of 3 runs as follows: The function recur is called; xl of6 is 0 TD0 called; is Tc(x-2)Tj213nction cal-3ca1851nction Else6 0 TD(is cal1.9 T)s[(block 1 T)5.8(

107

' example file VBA-Concepts.xls, Module "LoopsAndConditions" Sub macro_if() Dim number As Variant number = InputBox("Type in a number, please!") If Not IsNumeric(number) Then MsgBox "This is not a number!" ElseIf number > 10 Then MsgBox "The number is larger than 10" Else MsgBox "The number is greater than or equal to 10" End If End Sub

In addition to conditionals various functions can also return a truth value, such as the IsXxx functions, which determine whether an expression corresponds to a particular data type (IsNumeric, IsDate etc.). In VBA you can join several comparisons together. In this case as well the result of the entire expression is a truth value. The first example below tests whether a is less than 5 or greater than 10, while the second example tests whether a

Sub macro_select() Dim number As Variant number = InputBox("Type in a number, please!") Select Case number Case 1, 2, 3 MsgBox "1, 2 or 3" Case 4 To 10 MsgBox "Between 4 and 10" Case Is > 10 MsgBox "Greater than 10" Case Else MsgBox "Less than 1" End Select End Sub

The syntax of Select Case

The design of a For loop is such that it may not be executed even once. That is because even before the first pass through the loop it is checked whether the loop conditions are valid. A loop that begins For i=5 To 1 will thus not be executed even

Sub macro_loop6() Dim i As Integer i = 1 Do Debug.Print i i = i + 1 Loop Until i > 10 End Sub

Loops with WhileWend


Loops with WhileWend offer nothing new with respect to the loops with Do Loop. The only difference is that there is now the possibility of terminating the loop prematurely with Exit.
While i < 10 i = i + 1: Debug.Print i Wend ' Do While i < 10 Loop ' the same loop [[?]] i = i + 1: Debug.Print i

Syntax Summary
Below, square brackets enclose optional commands, which may be given but do not have to be.
DEFINITION OF PROCEDURE

Sub macro( [parameterlist] )

LOOPS WITH FOR NEXT

For var=start To end [Step value] commands


[If condition Then Exit For]

commands
Next var
LOOPS WITH FOR EACH NEXT

For Each var In enumeration method or field() commands

4.3 Objects Working with Objects, Methods, and Properties


Objects

In VBA elements of Excel are called objects. The following list enumerates the most common objects: Application (the Excel application in its entirety), PageSetup (page setup for printing), PW59.78(o0.21()19.76(kbook]TJ/F1 1 Tf-4.722 -0TD-0.0001 Tc[0.0001 Tcw

means property. Enumeration objects such as Sheets represent an exception, since they can be used both with and without parameters. It is not always possible to distinguish methods and properties from their internal aspects: Many actions that are carried out in VBA by methods could be managed just as well by differently formulated properties, and vice versa. In the end, it is the folks at Microsoft who have determined what is a method and what a property. We leave it to you to judge whether there is madness to their methods! To distinguish between objects and both methods and properties the following rule might be formulated: Objects almost never appear directly in the instructions of program code. Even if it often seems as though objects are being named directly, it is always a like-named method or property that is at issue. There is an important exception to this rule: In the declaration of object variables, objects (more precisely, object classes) are named directly.

Example 1
The following instruction appends a blank chart sheet to the current workbook. This example demonstrates several aspects of dealing with objects: the interplay of objects, methods, and properties; the use of named parameters; the use of predefined constants:
Application.ActiveWorkbook.Sheets.Add Type:=xlChart

Application gives the root object (the application program Excel). ActiveWorkbook

Sheets.Add Type:=xlChart

ActiveSheet.Name = "My Chart"Syvvv!h $4#*!6y64nstead(of(the(two(lines(abo*Lky54ve(a(single(somewhat(longer(line(wil(sufice_*]%(fs&y2(v(v(&y2(!v&(5T!yL&262y6

Access to Active Objects


Excel recognizes a number of active objects, meaning marked or selected parts

Figure 4.1. The Object Browser

Figure 4.2. The References form

Within With

Many objects can also be declared with Dim x As New Object. In this case the corresponding object is created immediately. This syntax is normally possible only with object classes that are made available through external libraries (ActiveX server) or are defined by Excel class modules (see the following section). Above all, object variables are used to make a more readable organization of

Automatic Opening of Excel Files


All files located in the directory Xlstart are automatically opened when Excel is launched. In conjunction with an

CAUTION In normal modules Application is considered a default object, in that all methods and properties derived from it can be used without Application being explicitly named. In modules associated to Excel objects (such as This Workbook, worksheets, chart sheets), on the other hand

Deactivating Event Procedures


The one serious disadvantage of the new way that events have been conceived since Excel 97 is that activating and deactivating events using program code is difficult. For example, if you wish temporarily to deactivate the call to a specific event procedure, you have to employ the following code:
' in the class module of a worksheet Public activateEvents Private Sub Worksheet_Activate() If activateEvents <> True Then Exit Sub MsgBox "Worksheet_Activate " & Me.Name End Sub

deactivE eveT

since E

The following description is limited to the most important events of the objects Workbook and Worksheet, which are particularly simple to execute in the development environment. Furthermore, the four still-supported OnEventXxx events will be treated here in accordance with the old event concept. The syntax summary at the end of this section lists all events for several important Excel objects.

Open and Close File (Events Open/BeforeClose)


After an Excel file has been loaded, the procedure Workbook_Open is executed if it exists. Analogously, when a workbook is closed (that is, when Excel is terminated), Workbook_Close

is extents

s tat

However, ti9.5(e exist countless ot objects tat can tr)-8.1(igg .6(515 Tmt c9.5n)]TJ-1.8947 -1.42

The code consists of two parts: The event procedure is defined in the class module ClassAppEvents. A reference to the new Workbook object is automatically passed to the procedure NewWorkbook.
' file VBA-Concepts.xls, class module "ClassAppEvents"

POINTER Starting with Excel 2000 you can program new classes with their own events (see the next section). The addition of event procedures in Excel files described here has nothing to do with that capability.

The VBE Library


In this book we are not going to give a detailed description of this library. However, to understand this example it is necessary that you at least know the most important objects: VBE VBProject[s] VBComponent[s] CodeModule Properties/Property
start object (access via Application.VBE) projects (Excel files) modules, classes, forms of the file, etc. code of the components access to an objects properties (properties window)

The most interesting methods for this example, CreateEventProc and InsertLine

NOTE Code that uses the VBE library can be executed in Excel 2002 only if theoption OOLS

WorkbookDeactivate

change of active workbook new sheet added to the workbook the workbook was just opened

WorkbookNewSheet
WorkbookOpen
WORKBOOK EVENTS

Activate AddinUninstall
BeforeClose BeforePrint BeforeSave Deactivate

the workbook was activated (change of window) the workbook was installed as an add-in the workbook is about to be closed the workbook is about to be printed the workbook is about to be saved the workbook was activated (change of window) a new sheet was added the workbook was just opened change of sheet

NewSheet Open
SheetActivate

SheetBeforeDoubleClick

CHART EVENTS

Activate BeforeDoubleClick BeforeRightClick

change of sheet (or chart) double click

Initialize and Terminate Procedures


The procedures Class_Initialize and Class_Terminate can be defined within class modules. These procedures are automatically executed when an object of the class is generated, respectively when it is later deleted. These procedures can be used only for initialization and cleaning-up tasks.

Class Hierarchies with Implements (New in Excel 2000)


Often, one would like to define an entire group of associated classes, for example, a superclass

Property Get XMean() As Double Dim p As XYPoint, xm As Double If points.Count = 0 Then XMean = 0: Exit Property For Each p In points xm = xm + p.x Next xm = xm / points.Count XMean = xm End Property

Example for Derived Classes (Implements

Private Sub

The Derived Class Magazine


The class Magazine as well is derived from Document, and this class, too, was extended with an additional property, called Articles. In contrast to Book, the properties Title

End Property

The values of these constants correspond to the powers of 2 (20, 21, 22, 23,

Event procedures and the

C HAPTER 5

Techniques of Programming
T8 506.6429 Tm(T)Tj7.12 27F1 3 398/5ers

3(.................................................................128 506.46.9429 5)T1 0 0 3858 506.6429 Tm(T)T

5.1 Cells and Ranges of Cells

It is possible to edit a range either directly or via the detour of selection. In the first variant the properties and methods of a range are executed immediately after the Range method is executed, as in, for example, Range(A1:B2).Count. In the

ActiveCell returns Nothing if no worksheet is displayed in the active window (for the Application object) or in the given window. ActiveCell cannot be used for a particular worksheet. (This property is defined only for the Application object and the Window object.) If you wish to determine the active cell of a worksheet that is not currently active, you must first make this worksheet the active sheet of the current window with Worksheets().Activate. Selection: This property is, like ActiveCell, defined only on the Application and Window levels. It refers to the object that has just been selected in the current win-

GoTo: This method selects a range, and is thus comparable in its effect with:Saeects]TJ/F1 1 T

Areas: This method is similar to Cells, but it returns connected (rectangular)

Determining the Address of a Range of Cells


Address: This method returns the address of a range in the form of a character string. If the range A1:B4 is selected, then Selection.Address returns the string $A$1:$B$4

cells to the right or below are promoted to the vacated location(s) (this corresponds to the command EDIT|DELETE). For inserting new cells into the worksheet there exists the method Insert. It is similar to Delete

Formula returns or expects the formula in English. The formula is also saved internally in this format and is displayed with the properties of the local language

In VBA, styles are invoked as Style objects. Every Excel file (Workbook object) can use Styles to access available styles in the file. Some format templates are predefined (Builtin=Trutyleome f 6filF1 41 6fil83.2 64083.2352.8 57 m.0003 TcTj-31/4.0200.005294.02

The last property left to be explained is NumberFormatLocal. This propertys documentation is practically nonexistent. Experiments with the German version of Excel has shown that there is no simple one-to-one translation of code into the local format. For example, the position of the currency symbol is shifted. With the format Currency positive numbers are formatted, according to NumberFormat _($* #,##0.00_) (that is, with the currency symbol before the number). However, according to NumberFormatLocal they are formatted with _-* #.##0,00 _-(that ne(, with the curr)19.6(ency symbol NormatLocal is shifted. (e is end)29.f5.8586 0 TD18.00402 Tc0 Tw[(N)23.erF

A1 Versus R1C1 Notation


In general, cell references are given in the A1 notation. Range(R1C1) is not permitted. In program code it is often more practical to set cell references with Cells. This method expects numeric parameters as input of the row and column numbers and therefore corresponds to the R1C1 syntax. Formulas in worksheets represent a special case. With the property Formula the formula of a cell in the A1 format can be read or edited, while FormulaR1C1 does the same for the R1C1 notation, and FormulaR1C1Local in, for example, the Z1S1 notation in the German version (Zeile

End If Next colNr If cell2 Is Nothing Then Set cell2 = Cells(rowNr, 256) ' select the range between cell1 and cell2 Range(cell1, cell2).Select End Sub

The loop could have been formulated differently (though less elegantly):
Dim i As Integer If Selection Is Nothing Then Exit Sub For i = 1 To Selection.Cells.Count

Chapter 5

The following macro offers a solution. It removes all borders of the previously selected cells, even if the borders actually belong to a neighboring cell:
' example file Cells.xls Sub RemoveAllBorders() Dim calcMode&, updateMode&, i Dim rng As Range, ar As Range Dim brd As Border If Selection Is Nothing Then Exit Sub ' speed optimization calcModue = Application.Calculation updateModue = Application.ScreenUpdating Application.Calculation = xlManual Application.ScreenUpdating = False ' For Each ar In Selection.Areas For Each rng In ar ' for each region of cells ' for each cell

' delete all borders of the current cell For Each i In Array(xlEdgeTop, xlEdgeBottom, xlEdgeLeft, _ xlEdgeRight, xlDiagonalDown, xlDiagonalUp) rng.Borders(i).LineStyle = xlLineStyleNone Next i ' remove the right border of the cell bordering on the left If rng.Column > 1 Then rng.Offset(0, -1).Borders(xlRight).LineStyle = xlLineStyleNone End If ' remove the left border of the cell bordering on the right If rng.Column < 256 Then rng.Offset(0, 1).Borders(xlLeft).LineStyle = xlLineStyleNone End If ' remove the lower border of the cell above If rng.Row > 1 Then rng.Offset(-1, 0).Borders(xlBottom).LineStyle = xlLineStyleNone End If ' remove the upper border of the cell below If rng.Row < 65536 Then rng.Offset(1, 0).Borders(xlTop).LineStyle = xlLineStyleNone End If Next rng Next ar ' end speed optimization Application.Calculation = calcMode Application.ScreenUpdating = updateMode End Sub

210

Speed Optimization
The execution of a procedure that makes extensive changes in a worksheet can be quite slow. Two possible reasons for this are the time it takes for constant updating

SolverOptions MaxTime:=100, Iterations:=100, Precision:=0.000001, _ AssumeLinear:=False, StepThru:=False, Estimates:=1, _ Derivatives:=1, SearchOption:=1, IntTolerance:=5, _ Scaling:=False, Convergence:=0.0001, AssumeNonNeg:=False SolverOk SetCell:="$A$6", MaxMinVal:=1, ByChange:="$A$7:$A$8" SendKeys "~" 'corresponds to <Return> SolverSolve

TIP You have to set a link to the Solver Add-In in the VBA development environment with TOOLS|ADD-INS before you can use the Solver Add-In.

INSERTING AND DELETING DATA IN CELLS

range.ClearContents range.ClearFormats range.Clear range.ClearNotes

clear content of cells clear formatting of cells clear content and formatting clear notes

range.Delete [xlToLeft or xlUpear notes

5.2 Workbooks, Windows, and Worksheets

Important Properties of Workbooks


Name, Path ath[(Pa)-39.8(t)-393232 N N

Important Properties of Windows


WindowState: This property determines the appearance of a window. Possible values are xlMaximized, xlMinimized (icon), xlNormal. Visible: This property tells whether the window is visible (True) or invisible , should to displaymiz: (False). Invisible windows are said to be hidden (command WI9,

This property d

TIP To be precise, there is also a fourth type of sheet, which, however, has not been supported since Excel 97: module sheets (object type Module). Modules were displayed in Excel 5/7 as worksheets, but since Excel 97 they can be edited only in the VBA development environment. Note, however, that in the loop For Each s In Sheets

The Most Important Sheet Properties

' example file Sheets.xls Sub ShowWindowsAsIcons() Dim win As Object For Each win In Windows If win.Visible Then win.WindowState = xlMinimized Next win End Sub

Splitting Windows at the Current Position of the Cell Pointer


The following example program splits a window at the current position of the cell pointer. If the division of the window was previously fixed, then it will again be

Deleting a Sheet
For deleting a sheet, all that is necessary is to execute the Delete method. The problem is in the safety alerts that Excel displays before deletion. In some applications it could be an irritant to the user to be confronted suddenly with an alert generated not by the user, but by the program. For this reason the property DisplayAlerts can be used to deactivate such alerts during macro execution.
Sub DeleteActiveSheet() Application.DisplayAlerts = False ActiveSheet.Delete Application.DisplayAlerts = True End Sub

One final suggestion: This procedure is not able to delete a sh ane 54.3123 Tedul1 1 TfTD894

WORKING WITH WINDOWS

win.Activate win.ActivatePrevious win.ActivateNext win.Close win.NewWindow

activates the specified window activates the previously active window activates the next window in the list closes the specified window evtes tanexwwindow

5.3 Data Transfer via the Clipboard Copying, Cutting, and Pasting Ranges of Cells
If you wish to relocate or copy a range of cells, your best bet is to use the clipboard, just as in using Excel manually. The following methods are designed for data transfer to and from the clipboard. Copy

TIP Starting with Office 2000, Excel, Word, and the like possess not merely one clipboard, but twelve. In other words, the last twelve cut or copied data are in temporary storage and can be restored as needed. For this you need to make the toolbar Clipboard visible. However, this new feature is not accessible to VBA programmers. The commands described in this section are valid only for the last piece of data added to the clipboard. The up to eleven remaining clipboard items cannot be accessed by code.

Copying a Range of Cells into Another Sheet


The following instrus.

Rounding Numbers
In Excel and in VBA there are numerous functions that supposedly round. However, not a single one of these functions adheres to the simple mathematical formula whereby a number with fractional part 0.5 is rounded up to the nearest integer. The functions CLng and Application.WorksheetFunction.Round come the closest. CInt and CLng

Functions for Working with Character Strings


The three most important character string functions are Left, Right, and Mid. Left

The Concatenation Operator &


Several character strings can be joined together with the operator +. For example,

The function Val is quite different from the functions discussed above. The most important difference is that in all cases a period must separate the integer and fractional parts of the number. The function returns its result automatically in the appropriate data type, and thus behaves like a Variant variable. Val is much less allergic ues liktompgic ualidtomput. F(The7(ortomsdifc5(, and t/F6 1 Tf4.09218.86960 Tw[(V

New in Excel 2000 are the functions FormatNumber, FormatCurrency, and FormatPercent for formatting numbers, and FormatDateTime for formatting dates and times (see the next section). While these functions are less flexible than Format, they make up for this lack of flexibility by being easier to use. These functions use optional parameters, of which the first usually gives the number of digits to the right of the decimal point. The basic settings are taken, as with Format, from

ROUNDING

CHARACTER STRINGS (CONTINUED)

InStr(n, s1, s2, 1) InStrRev(s1, s2 [,n])

as above, but case-insensitive like

TRANSFORMATION FUNCTIONS (CONTINUED)

Val(s) Str(v) Format(v, s) FormatNumber(v, n)

returns the value of the character string transforms a number into a character string returns a character string, whe Tc[7n9.format instruction in s is applied formats x as a number with n decimal places

nature, and it could change in the future (with a different operating system or ver-

Dates and Times in Program Code


In VBA procedures dates and times are enclosed between two # signs, for example, #12/31/1999# or #17:30# or even the combined #12/31/1999 17:30#. Sad to say, Excel turns #17:30# into #5:30:00 PM#, whether you want it to or not, but at least it accepts #17:30#

So that you do not lose your overview entirely, the following description goes subsection by subsection. First are described the functions that can be employed in VBA code. Then worksheet functions are described, with like-named functions referred to in the first section. We then go on to demonstrate application techniques in both worksheets and VBA code. The next subsection goes especially into the problem of holidays, which vary from country to country and thus cannot be

If invalid dates resuldres rsuch as 4/31), then asictur

Number of Days in the Current Month


=DATE(YEAR(d), MONTH(d)+1,1) - DATE(YEAR(d), MONTH(d),1) DateSerial(Year(d),Month(d)+1,1) - DateSerial(Year(d),Month(d),1)

Number of Days in the Current Year


=DATE(YEAR(d)+1,1,1) - DATE(YEAR(d),1,1) DateSerial(Year(d)+1,1,1) - DateSerial(Year(d),1,1)

Number of Days in the Year Until a Given Date


=1+d-DATE(YEAR(d),1,1) 1 + d - DateSerial(Year(d),1,1)

The formulation in VBA is somewhat more complicated, but in exchange it is easier to read:
diff = Year(d2) - Year(d1) If d2 < DateSerial(Year(d2), Month(d1), Day(d1)) Then

If Weekday(startdate + i) = calcWeekday Then dayCounter = dayCounter + 1 If dayCounter = number Then NumberedWeekday = startdate + i End If End If Next Else ' last, next to last weekday in a month startdate = DateSerial(calcYear, calcMonth + 1, 0) 'last day of m. For i = 0 To 27 If Weekday(startdate - i) = calcWeekday Then dayCounter = dayCounter - 1 If dayCounter = number Then NumberedWeekday = startdate - i End If End If Next End If End Function

HolidayTable(year) creates a list of all holidays for the given year and stores

TIP

In this section the new File System Objects take center stage. The tradi-

FILESYSTEMOBJECT : OBJECT HIERARCHY

FileSystemObject Drives Drive

top of the object hierarchy listing of drives and partitions Drive object for describing the drive

DRIVE: OBJECT HIERARCHY

Drive RootFolder Folder

Drive object refers to drives root folder (directory) Folder object

FOLDER: OBJECT HIERARCHY

Folder Drive Files P-9119(a)0s to dr

Folder object Drive object listing of all files in folder

Files.Count returns the number of files, but the files themselves can be processed only in a ForEach loop. These File objects for the most part exhibit the

Recursively Processing the Directory Tree


It often happens that instead of working on all files within a given folder (search,copy, and soon ),

Example
CreateTextFile

Binary Files
In the above example numbers and text were stored in text format. But there is also the possibility of storing numbers in Visual Basics internal format. This for-

For loading and storing data in binary format we have the commands Get and Put. Put stores a number or a character string. H,d storing daws,vcre6o

dialog. The return value True means that the selection was terminated with OK. Now the selected file or dirmy names can b raomthe senumr

Text Import Wizard for Interactive Importing


Aid in reading such files is offered by the text import wizard. This assistant appears

t h Figure 5-6. Input of the column breakpoints in the text import wizard for importing the file german.txt

For scientific.txt the wizard knows all by itself that the columns are separated by tabs. In the third step the date format must be set according to the region.

CAUTION

With the macro recorder onlM.tecorder onlM.F Tf9fcorf(der onmcor)ft this can leadrt

SS351[(S2as abo)29.5(ve)19.6(, but column separ)9.5(ator is the semicolon.)]TJ 0 9 108 6-101-1.7778TTD T

ro

recorder

only

those

imS

Tf9-7(i)t

settings

a25.8(eco

sho).6

7(w(i)t

settings

ao

s&se

imS

Tf9]TJ-(W)9)T338.0(i)[(diffe

imS

Tfnt

f5.8(derm8(ecodefaulo

sho).6

imS

Tfgional

sho).6

!)

I)S

Tffrecocodings

lat9-7e5.76(x)S

9(e-9]TJ4[(cuted7(i

aocomput9-7wi5.8a

diffe

imS

Tfnt

imS

Tfgional

sho).6

,)-18i

r25.en

une5.76(xpected7p5.8(derb-9]TJ4[(lemsocouldse

ise,)-18i

r2since

o5.erodefaulo

sho).6

.TextFileStartRow = 1 .TextFileParseType = xlDelimited .TextFileTextQualifier = xlTextQualifierDoubleQuote .TextFileConsecutiveDelimiter = False .TextFileTabDelimiter = True .TextFileSemicolonDelimiter = False .TextFileCommaDelimiter = False .TextFileSpaceDelimiter = False .TextFileColumnDataTypes = Array(1, 3, 1, 1) .TextFileDecimalSeparator = "." .TextFileThousandsSeparator = "," .Refresh BackgroundQuery:=False End With End Sub 'here the importing is triggered

To repeat the importation at a later time, you need only execute

TIP There are many other formats for saving a file or worksheet, such as HTML document, Unicode file, or database (dBase format).

Text Exportation for Mathematica Lists


The procedure SaveRangeAsMmaFile saves a previously selected range of cells in a text file, using the list format of Mathematica, which can later use the file. (Mathematica

If a valid range has been selected, then the method GetSaveAsFilename is executed in the function SelectFilename. A dialog box appears for selecting a file name. If the name of an existing file is chosen, then the program displays an alert in a MsgBox. The user must affirm the overwriting of the file by clicking YES . The file selection is placed in a loop so that the user has the possibility of selecting a new file name. The loop is executed until the user has selected a valid file name or has canceled the selection process.

Saving Data in SaveRangeAsMmaFile


The function SelectFilename returns the file name to the procedure

In the program

IMPORT / EXPORT

5.7 User-Defined Worksheet Functions Fundamentals

Cell Ranges as Parameters


If a user-defined function is called with a cell reference (such as =Discount(A1,B1)), then a Range

Error Checking
If you wish to program a function that is not conceived for ranges of cells, but exclusively for individual values, you should use an error check to exclude the possibility of invalid parameters being passed. The function Discount thus protected would look something like the following:
Function Discount(unitprice As Variant, pieces As Variant) As Variant On Error Resume Next If TypeName(unitprice) = "Range" Then If unitprice.Count > 1 Then Discount = CVErr(xlErrValue): Exit Function End If End If If TypeName(pieces) = "Range" Then If pieces.Count > 1 Then Discount = CVErr(xlErrValue): Exit Function End If End If If pieces >= 10 Then Discount = pieces * unitprice * 0.95 Else Discount = pieces * unitprice End If If Err Then Discount = CVErr(xlErrValue) End Function

CVErr(xlErrValue) returns a variant data type of subtype Error containing an error number. In a worksheet, you see #VALUE in the cell in which the function is used. More information on the subBr

The Volatile Method


With the instruction Application.Volatile a user-defined function can be set as volatile. (Normally, functions are recalculated only when their precursor, or precedent, cells change. This is usually sufficient and certainly much more efficient.)
Public Function VolatileTest() As Double Application.Volatile True VolatileTest = Rnd End Function

If you input the formula =VolatileTest() into a cell, the indicated value will= (into athe fo0Ated

'example file function.xls; Function NumberToText(x As Variant) As String Dim i&, result As String, character$, lastchar& Dim digit$(9) digit(0) = "zero": digit(1) = "one": digit(2) = "two"

AverageProduct

Public Function HighestAverageArgument(ParamArray p() As Variant) As Variant Dim nrOfRanges&, i&, maxnr& Dim averg() As Double, tmp As Double nrOfRanges = UBound(p()) ReDim averg(nrOfRanges) ' and store in a field For i = 0 To nrOfRanges If TypeName(p(i)) <> "Range" Then HighestAverageArgument = CVErr(xlErrValue): Exit Function End If If p(i).Areas.Count > 1 Then HighestAverageArgument = CVErr(xlErrRef): Exit Function End If averg(i) = WorksheetFunction.Average(p(i)) If Not IsNumeric(averg(i)) Then HighestAverageArgument = CVErr(xlErrValue): Exit Function End If Next ' find highest value For i = 0 To nrOfRanges If averg(i) > tmp Then tmp = averg(i) maxnr = i End If Next ' return result; plus 1, thus 1 for the first range ' (and not 0) HighestAverageArgument = maxnr + 1 End Function 'UBound returns 2, if 3 parameters ' are passed

' calculate average value for all ranges of cells

5.8 Protection Mechanisms


In setting up Excel tables and applications it frequently happens that you wish to

which are passed as binary DLL. But they have many other drawbacks. In particu-

In progr, cells can be locked b py

Protecting the Entire Workbook


With TOOLS|PROTECTION|PROTECT WORKBOOK you can protect the sequence of sheets in a workbook and/or the arrangement of windows. With the second of these you

Figure 5-12: New Protection Options in Excel 2002

From the point of view of the developer, the Protect method for the Worksheet object has been extended by a host of parameters that allow control over the objects shown in Figure 5.12. Which protection options are currently in force can be determined with Worksheet.Protection. This property refers to the like-named Protection object, whose properties AllowFormattingCells, AllowSorting, etc., give information about

Protection Mechanism for Shared Workbooks


Since Excel 97 it has been possible to save an Excel file in a special file-sharing for-

Protecting ToolBars
To protect toolbars and user-defined menus from being changed you can set the Protection property of the CommandBar object. There are eight possible values to be set, by which the content, position, and visibility of the object can be protected from changes (msoBarNoProtection, msoBarNoCustomize, msoBarNoResize, msoBarNoMove, msoBarNoChangeVisible, msoBarNoChangeDock, msoBarNoVerticalDock, and msoBarNoHorizontalDock). These protection functions are available onlkable 1 Taobject can bmodel. A frotection mso(%:)%"##:F6

1ET0

5.9 Configuration Files, Custom Configuration


There are numerous ways in which Excel can be configured to the users specifications: custom toolbars, changing and extending the menu system,

With FILE|SAVE A

The settings for the page format, headers and footers, and so on, are carried out with the PageSetup object, which is set for every sheet object (WorkSheet, Chart, etc.) and can also be addressed with the Window object. It is not possible to change all at once the page format of several sheets through program code. (Execute a loop over the sheets in question and change PageSetup for each individual object.) The active printer, on the other hand, is set with the ActivePrinter

PAGESETUP OBJECT (PAGE LAYOUT, SET SEPARATELY FOR EACH SHEET)

BlackAndWhiteprint in black and whiteBottomMarginpBottomMenterHeader 1 TwD[(p)]TJ/F1c enter

Configuration Files
Basics
Most current operating systems are automatically configured in such a way that a personal directory (folder) is available to each user (that is, for each login name or

These settings can be edited with the programs RegEdit.exe andegEd%W4?kMpM4?t._vMW

G te hs _

_ gnisuac

_ hcum

ras ec n u _ y

G k row _

_ hcus

sa

Add-In Files
As you can read in Chapter 14 in full detail, Excel recognizes two types of add-ins. Traditional add-ins are in principle normal Excel files, which, however, are stored as add-in files with the file extension

It remains only to explain

In Excel 2002 these same problems occur. The error alerts look a bit different, but they are just as confusing as ever. The reason for the second error alert remains completely opaque. Fortunately, however, there is a simple solution: Before passing on your file, switch into the development environment with Alt+F11 and establish a reference to EuroTool. (This library will be displayed automatically once the euro add-in has been activated; see Figure 5.17.) If the file thus prepared is now opened on a computer on which the euro add-in has not been activated, everything functions correctly anyhow. (To be sure, the add-in remains inactive, but theTutom2(T)9etheless loaded, and the Euroconvert function is available both in theworksheet and as VBA code.) The only requirement is that the euro add-in be installed on the computer. If thatom2(T)t the case, then there appears, alas, T should be installed, but an error alert, which give2(T) indication as to the cause of the trouble (Figure 5.20).

Figure 5-20. Error alert if the euro add-in has not been installed

Thus you have(T) choice but to advise the user somewhere at the beginning of the worksheet that thm2(Tutouses the eur)5.7(o add-in and that the user should install it)]TJT*-0.0 maorkFandfbrncsh into euroe.U fort om2simoassblue. Theoconlestion ofccuprncyeocotinueas y to be

In many tables there are cells in which the source number is input not as a number (such as 1200), but as a formula (say, =1000+200

If these preliminary tasks have been accomplished, open the file to be converted and save it at once under a new name. (This is to ensure that the changes hold for the new file only, while the original file, if only as a control

Chapter 5

Figure 5-23. The table after euro conversion

If you in fact marked the correct cells, then the euro conversion is complete (Figure 5-24). (If you neglected to mark some cells, then simply repeat the above process: first mark cells, then convert them.) However, in the last step result cells like E3 must be formatted. The correct amount in euros appears, but it is formatted as for German marks. The fifth

350

Program Code

Sub ConvertNumberIntoEuro() Dim calcMode&, updateMode& Dim cell As Range If TypeName(ActiveWindow.ActiveSheet) <> "Worksheet" Then Exit Sub ' speed optimization calcMode = Application.Calculation updateMode = Application.ScreenUpdating Application.Calculation = xlManual Application.ScreenUpdating = False ' for all cells of the worksheet For Each cell In ActiveWindow.ActiveSheet.UsedRange If Not IsEmpty(cell) Then If cell.Borders(xlDiagonalUp).LineStyle = xlConoRushen If cell.Borders(xlDiagonalUp).LiCol Ea= vbR opNmxen

The euro formatting procedure EuroNumberFormatRange

Room for Improvement


If Euro.xls were a commercial product, then there would be some work left to be

Sub HighSpeed() Dim calcMode As XlCalculation, updateMode As Boolean ' ' begin speed optimization calcMode = Application.Calculation updateMode = Application.ScreenUpdating Application.Calculation = xlManual Application.ScreenUpdating = False ' ' here place the actual code of the macro ' ' end speed optimization Application.Calculation = calcMode Application.ScreenUpdating = updateMode Application.Calculate End Sub ' recalculate everything (if necessary)

The procedure HighSpeed saves the current values of bothF6 1 Tf623aves t*(uif6atnt v0081 -13

The text of the status bar is set with Application.StatusBar

' miscellaneous.xls, Module1 Sub slowcode() Const loopEnd = 1000000

Program Interrupts

The above example begins and ends with several lines that ensure the orderly ter-mination of th

xlCalculating (the recalculation is currently taking place), or xlPending

Working Efficiently with Worksheets


It is in the nature of Excel applications that in many cases their main purpose in life is to process enormous worksheets (read or write values, change them, analyze

Work with fields: Accessing field elements proceeds much more rapidly than accessing cells. Fields can have all their calculations carried out and then copied as a unit into a range of cells. Work with data fields: Data fields have many disadvantages as compared

Dim x As Variant x = Worksets(1).[a1:b4] 'read 8 elememEt

SPEED OPTIMIZATION

ScreenUpdating = True/False Calculation = xlAutomatic/xlManual object.Calculate

screen updating on/off automatic/manual calculation recalculate range/sheet/entire application

Below, rc stands for row or column (Row

debugging

process.)

The

purpose

of

this

chapter

of

new

functions

being

discovered.

(We

shall

pass

over

in

silence

Therefore, always use the option Explicit. If you click on the option REQUIRE VARIABLE DECLARATION in the form TOOLS |OPTIONS | EDITOR , then VBA automatically adds the instruction O p to t every inew module. o (This n option has E no x effect on preexisting modules.) If you give the type of your parameters explicitly in your procedures (and you should), then this type must match exactly the type of the variable passed when the procedure is called. Otherwise, an error alert will result.

Reaction to Errors

In TOOLS |OPTIONS |GENERAL you can select from amm 0 9fTJ/F4 1.4517 Tm0.021u775ameppg motion

The Immediate Window as a Debugging Tool


An important assistant in debugging is the immediate window. You can open the immediate window before a procedure is launched with VIEW|I

' file VBA-Concepts.xls, Module Procedures Public Sub testrecur() Debug.Print recur(3) End Sub ' recursive procedure for calculating the factorial of x Function recur(x As Double) As Double If x <= 1 Then recur = 1 Stop Else recur = x * recur(x - 1) End If End Function ' here the execution is interrupted

Program Changes in a Running Program


Since Excel 97 it has been possible to make changes in a running program and then continue execution. Needless to say, this is a very practical method of debugging. However, continuing the program is not possible if the structure of the program changes, such as in the declaration of a parameter of a currently active procedure. If you activated the option NOTIFY B

Control Output in the Program


In many cases it is useful to have the program output control information. For this there are two possibilities: You can use the command MsgBox to output an arbitrary (short) text in a

Figure 6-2. Defining a watch expression

Figure 6-3. The Watches window

The ADD WATCH form is particularly attractive if you wish to examine the prop-

6.2 Error-Tolerant Behavior of Programs


Normally, an error causes an interrupt. VBA displays a dialog box by means of which program execution can be terminated or the code analyzed in the immediate window. A continuation of the program is essentially never possible. During program development interrupts due to errors are unavoidable. However, a user who uses an Excel program developed by you should never encounter a dialog box

Sub test_resume_next() On Error Resume Next

ActiveWinddwl2aDisplayHeadG2wddgs = _TjnNFR2mw0zW)TDn=ONot tiveWinddwl2aDisplayHeadG2wddgsjnNFR02mw0zW)TDn=OE

Sub test_resume() On Error Resume test_resume_error ... test_resume_cont: ... Exit Sub test_resume_error: .. Thei r On Error Resume test_resume a o thre_error ..b '_repco sme o a'_rcogo izued_error ' End of the procedure ' b a dlti g rouwti e begti s' herr ' here the procedure is continued after an error

test_resume_ ...

'_repcoukwror

test_refe=dsG2dldCu O(mG NC tss.s 0.,. :

If result = vbYes Then Resume Next End If ' otherwise, interrupt procedure ' ' .. cleanup tasks End Sub

Figure 7-1. Dialog box for arranging windows

The syntax of the character string in which the simulated keyboard input is given in SendKeys is described extensively in the on-line help for this method. In principle, it is also possible with SendKeys to terminate the input in the dialog at once with Ok (that is, by simulating Return). In this way you can execute various Excel commands directly via the detour of a dialog box. If the property ScreenUpdating is set to False, then the user of your program doesnt even see the dialog box. Nonetheless, this method is not to be recommended, for the following three reasons: By executing the appropriate methods the same result can be achieved usually more simply and always significantly faster. (However, it is not always

Figure 7-2. Save As dialog (GetSaveAsFilename )

Instead of this you can and also useu c c-thods GetOpenFilename

GetSaveAsFilename. Thenu c cfile selection dialog box will be displayed, but only

Warnings
Many unwanted forms can appear during the execution of methods. Usually, these are in the form of warnings that advise against the consequences of the operation (such as loss of data). For example, with the instruction Sheets(...).Delete for the deletion of a sheet of a workbook there appears an alert asking whether you

Figure 7-4. Message box

The Method Application.InputBox


Although the function

In calling this function you give the first parameter in the usual way, and the eighth by name:
Dim b As Range Set b = Application.InputBox("Please input a range of cells", _ Type:=8)

InputBox returns the affected selection in the format determined by the Type parameter. If the user ends input by pressing Cancel, then the method returns the Boolean value False. This situation makes the evaluation of the input for Type:=8 somewhat complicated: Since the result is normally a Range object, the assignment of the result must take place via Set. But this leads to an error if InputBox returns only the Boolean value False instead of a Range

in the lower left-hand corner of the screen. This is particularly irritating when you

Changes with Respect to Excel 5/7


Beginning with Excel 97 forms have been completely reconceptualized. Their development no longer takes place in an Excel dialog sheet but in a UserForm object of the VBA development environment. The UserForm object is one of the many objects in the so-called MS Forms library. This library also contains an object for every control. The unusual feature of the MS Forms library is that it can be used not only in Excel, but in other Office

Tips for Upgrading

Properties of Controls
Controls are equipped with countless properties, which are set in the properties window. In addition to the elementary properties Name (the internal name of the object) and Caption (the title), you there are properties for controlling the appearance and functionality of the control.

OK and Cancel Buttons


Almost every form is equipped with OK and Cancel buttons. To ensure that the form behaves like other forms to which you are accustomed, you should set the property Default

NOTE New in Excel 2000 is the possibility to give the optional parameter vbModeless with Show. With this you achieve that the form is shown with the property set to modeless. This means that the user can continue working in

Figure 7-8. The form for setting the tab order

If you wish to remove certain controls from the tab order, you simply set their TabStop property to False.

A list of controls at your disposal can be obtained by the pop-up menu command ADDITIONAL CONTROLS, which you can invoke from the toolbox window. To use these controls you must click on them in the form pictured in Figure 7-9. The controls will then be displayed in the toolbox, just like that for the MS Forms

The events KeyDown, KeyUp, and KeyPress enable a precise evaluation of keyboard events:

KeyPress: This event occurs when an alphanumeric key is pressed. The ANSI code for the input character is passed to the event procedure. In addition to the alphanumeric characters, the keys Return and Esc, as well as Ctrl combiReInr ptj/F1 1 Tf1.2.71 0 TD-0.0001 Tc(and )Tj/F9 1 nations, are reported. KeyPress

TEXTBOX

PROPERTIES

CurLine EnterFieldBehavior EnterKeyBehavior LineCount MultiLine PasswordChar Scrollbars SelectionMargin SelLength SetStart SetText TabKeyBehaviour Text
TEXTBOX

current line number

0 if the entire contents are selected upon activation True if upon Return a new line can be input
number of lines

True if several text lines are used


placeholder character for text tells whether scroll bars are to be shown with long texts

True if a space appears at the left margin, facilitating selection of whole lines of text
Length of selected text beginning of selected text selected text

True if Tab can be used to input a tab character content of the text box
METHODS

Copy Cut Paste


TEXTBOX

copy selected text to the clipboard cut selected text to the clipboard

insert text from the clipboard to replace selected text


EVENTS

Change KeyDown KeyPress KeyUp

text box contents have changed a key was pressed keyboard input a key was released

ListBox and ComboBox

The three listboxes that appear in Figure 7-12 are initialized in the following manner when the form is displayed:
Private Sub UserForm_Initialize() Dim i As Integer For i = 1 To 12 lstNormal.AddItem MonthName(i) cmbDropDown.AddItem MonthName(i) cmbCombo.AddItem MonthName(i) Next i End Sub

Figure 7-12. The three types of listbox

The number of the currently selected list element is accessible via the property ListIndex. (The numbering begins, as with all properties of the listbox, with 0.) Value

In btnOK_Click a test is made as to whether a valid selection of a list element exists (that is, ListIndex>0). If that is the case, the selected entry (property

LIST AND COMBOBOX

METHODS

AddItem Clear RemoveItem


LIST AND COMBOBOX

expand list delete list

delete list entry


EVENTS

Change
Click

element selection or text input with ComboBox element selection double click on a list element the dropdown list should be displayed (ComboBox only)

DblClick DropButtonClick

Check Box and OptionButton


Check boxes are useful for carrying out yes/no decisions. The current state is indicated by a check displayed in a small square. See Figure 7-15.

Figure 7-15. Check box and option button

The state of an option button is indicated by a dot in a circle. In addition to this visual difference, in comparison to the check box, there is a difference in func-

The current state of both controls is taken from the

Command Buttons and Toggle Buttons

commands in Form_Initialize have the effect of making the scrollable region correspond to the currently visible inside dimensions of the frame. (Scroll bars will then be required when either the zoom factor is increased or the frame decreased in size.) InsideWidth and InsideHeight specify the usable inside dimensions of the frame.

MultiPage, TabStrip
The controls MultiPage and TabStrip offer two ways of creating multipage forms. The resulting forms are indistinguishable, but the effort required to set up and program is more difficult in the case of TabStrippsogr contro.e

NOTE In setting the properties, take care that you have activatsgr(e that ct)]TJ-TD--1.30 70002 Tc

NOTE Originally, it was planned that ReadAttributes would be called in UserForm_Activate automatically each time the form was displayed. Because of a bug in Excel 97 the Activate event procedure is not reliably executed each time the form is displayed. For this reason ReadAttributes must be executed in code for calling the form before Show is executed.

WriteAttributes

MULTIPAGE

PROPERTIES

Pages Pages(n) MultiRow

refers to the Pages enumeration object refers to an individual Page object

Image
The Picture property is used to display a bitmap file on an object (image field). If a graphic is not placed in the properties window, but is to be loaded by program code, you can use LoadPicture:
Image1.Picture = LoadPicture("filename")

Figure 7-24. Result of the selection

REFEDIT

PROPERTIES

Value
REFEDIT

contains a character string with the cell reference


EVENTS

Change

Value has changed (unfortunately, the event is not always triggered)

The UserForm Object

A further advantage for worksheets is that all the formatting and calculational features of worksheets can be used in parallel with the controls. For example, a

TIP If you wish to insert controls into a worksheet, you must activate the CONTROL TOOLBOX toolbar. Take care that you do not accidentally activate the similar-looking forms toolbar. This toolbar contains the Excel 5/7 controls, which look the same but behave differently and are programmed differently as well.

There is no longer a simple mouse click for providing captions for controls. You have to select O

Dim sh As Shape For Each sh In Sheets(1).Shapes If sh.Type = msoOLEControlObject Then Debug.Print sh.Name, TypeName(sh.OLEFormat.Object.Object) End If Next

The next feature concerns initialization: When a worksheet with a listbox is loaded, no entry of this control is activated. ListIndex has the value 1. If this undefined state is unwished for, then a definite state must be established in Worksheet_Open (object This Workbook). For example, with ListIndex=0 the first entry cane 3 nctivated0Listboes, with(L)17.7(isS)219.7tyle=fm(L)17.7(isS)219.7tyleP la in[(

7.6 Programming Techniques Numerical Input


This introductory example displays a form for input of a number between 0 and 100 (Figure 7-26). The form exhibits two features of interest:

Reciprocal Calling of Forms


There are numerous possible applications of reciprocal calling of forms. If the user maketut erfors

The only particular issue in this example is the manual positioning of the forms: When form 1 is moved to another position by the user, forms 2 and 3 appear

Furthermore, you can place controls outside of the formou caovunda79.9()ies and

8.1 Menu Bars and Toolbars Manual Editing of Menus and Toolbars
Placing Toolbars, Hiding and Unhiding
Toolbars can be moved with the mouse and anchored, if desired, to one of the four borders of the screen or placed in their own toolbox windows. Excel keeps track of these settings, independent of the current mode. For example, Excel saves your settings for full screen mode. If you click with the right mouse button on a menu or toolbar, you open a pop-up menu (context menu) in which you can turn the most important toolbars

If you wish to add new commands or menus, you will find a complete (though confusing) list in the COMMANDS sheet of the CUSTOMIZE dialog (Figure 8-2). All the commands displayed on the right-hand side of this sheet can be copied directly with the mouse into a menu or toolbar. If you wish to copy a command into a

Chapter 8

Figure 8-3. Editing menu items and tools via the pop-up menu

Figure 8-4. The image editor

462

Groups
Several tools or menu commands can be brought together into a group. To do this, activate the option BEGIN A GROUP for the first entry of the group. A separator bar is then placed in front of, or above, the entry.

Assigning Macros
Each tool and menu item can be assigned to a macro. (In the case of predefined tools the result is that instead of the standard macro for this tool or menu command, the new macro will be executed.) This assignment is normally accomplished by way of the pop-up menu entry ASSIGN MACRO

Menu Bars and Toolbars (CommandBars)


Access to the

CAUTION If you attempt to create a new toolbar with Add using a name that is already in use, an error occurs. (The most probable cause is that you created the menu earlier and forgot to delete the program code.) You can catch the error either with On Error Resume Next (and evaluate Err in the following line) or before executing the Add command to run a loop through all toolbars to test whether one already exists with the name you wish to use.

Menu and Tool Elements (CommandBarControls)

Access to these objec.6(BTrl3m)-5sto 750 0 9[(aap8o 7[d commBrs.0(arCont thr6(ols0(/)]TJto -75

With Controls.Add

Text Boxes and Listboxes (CommandBarComboBox)


Text boxes and listboxes can be created only in program code, not with the

Programming Techniques

Adding and Deleting Menu Items via Program Code

CommandBarControl

Checks in Menu Items


It is often desirable to display a check next to a menu item to indicate its current state. This was easy in Excel 5/7 menus. One simply set the property Checked. In the versions of Excel starting with Excel 97 such checks are still possible, but the

Replacing the Standard Menu with a Custom Menu


Initial experiments with the CommandBar objects would lead one to believe that since Excel 97 (in contrast to previous versions) it is no longer possible to replace the standard menu with a custom menu. In interactive mode (TOOLBARS|C

Changing Sheets via a Toolbar


This section offers a concluding example for the possibilities of using toolbars in your applications: A toolbar is to be equipped with a listbox that enables a smooth change of sheets. When an Excel file grows to contain many sheets, navigation using the sheet tabs becomes rather cumbersome. The toolbar presented here contains a listbox (CommandBarComboBox) that simplifies the task (see Figure 8-7). The crucial task in programming is the synchronization of the listbox with the list of sheets of the currently active workbook. For this, two events of the

' new entry in tools menu Set cbb = Application.CommandBars("Worksheet Menu Bar"). _ Controls("Tools").Controls.Add() cbb.Caption = "A new command" cbb.BeginGroup = True

Cvls("are2p :=msre2pBarCPRbp3p) With cb,Tjo2=RDx2=R3/DT4oI)Controls.Addr"Aype:=msre2pControlB-bp3tTT-2Rn, Id:=3 hctave

Response to the Selection of a Listboxocedure "heetCombo_OnAction", which

movable listboxes (which then themselves form a toolbar; see the command C

COMMANDBARCONTROLS

METHODS AND PROPERTIES

Add Count
COMMANDBARCONTROL

add a tool/menu item/list number of menu items or tools


METHODS AND PROPERTIES

BeginGroup BuiltIn Caption Copy Delete

a group begins with the object

True for predefined elements


label text copies an entry from another toolbar delete entry

With the objects CommandBarButton

Since Excel 97 you can save new toolbars together with an Excel file (via VIEW|TOOLBARS|CUSTOMIZE|TOOLBARS|ATTACH). However, unlike what obtained in Excel 5/7, you cannot save any changes made to predefined menus and toolbars. Such changes are stored only in the file Excel.xlb. This file, however, cannot be passed to others. For this reason the second variant is the least problematic of the three. Although there is little concrete information about all of this in the Excel handbooks, one may suppose that this is the variant that Microsoft itself prefers. The following three sections describe techniques for implementing all three variants. In all the examples care is taken to make the alterations transparent, that is, to restore the standard Excel configuration when the file is closed or the sheet is changed.

Extending the Standard Menu

This section shows how an additional menu can be inserted into the standard menu when an Excel file is opened (in CommandBars(Worksheet Menu Bar)). This menu is automatically hidden when a sheet is clicked on that does not belong to the application. Moreovecelhe 7.12 0 0 7.12 1s1 Tf3ame iA similo tdarcoure m abac[(Th(Thihis

The second variant has the advantage that the creation of the menu can pro-

Figure 8-8. A new menu is inserted before the help menu in the main menu bar

The procedures Workbook_Activate and Workbook_Deactivate have the job of making the menu disappear when the focus is shifted to another file; when the workbook is activated once more, the menu reappears. The instruction On Error Resume Next prevents an error when the workbook is closed. In this case first Workbook_BeforeClose is executed, and there the new menu is deleted. Then Workbook_Deactivate is called, where the menu can no longer be accessed.
' activate/deactivate menu Private Sub Workbook_Activate() Application.CommandBars("worksheet menu bar"). _ Controls("new menu").Visible = True End Sub Private Sub Workbook_Deactivate() On Error Resume Next Application.CommandBars("worksheet menu bar"). _ Controls("new menu").Visible = False End Sub

When the file is closed, the menu is deleted from the standard menu bar. Furthermore, the toolbar is deleted, so that it is not saved in Excel.xlb.
Private Sub Workbook_BeforeClose(Cancel As Boolean) Dim standardmenubar As CommandBar Dim mycommandbar As CommandBar Dim c As CommandBarControl Set standardmenubar = Application.CommandBars("worksheet menu bar") Set mycommandbar = Application.CommandBars("CommandBar-Copy")

POINTER In the example file there is also demonstrated the programming of a menu item with a selection check. The backgd informaion cad associ-]TJ-T*[(mted tcode a)25.8

Figure 8-9. The example program has its own standard menu

In this program the procedures Workbook_Activate and Workbook_Deactivate

Templates are generally used in one of two variants: One may create empty worksheets in which merely certain formats are specified. Such templates have the purpose of saving the user effort in creating formats that are used over and over, such as the setting of print parameters and window options or the definition of frequently used styles. In this way it is possible to promote a uniform layout of all Excel worksheets produced by, say, an office or business: company logo on the first page, standardized headers and footers, uniform font, and so on. It is such more or less intelligent form templates with integrated VBA code that are the subject of this chapter.

Cell Protection
With TOOLS|PROTECTION|PROTECT SHEET you can protect all the cells of a worksheet from being changed. You may generally do without a password, unless you suspect that the user will intentionally make changes to the worksheet. Since it does not make sense to protect all the cells, since then no input could be given at all, before executing the protection command it is necessary to remove protection from the input cells. The dialog for this purpose is invoked with FORMAT|CELLS| PROTECTION or the pop-up menu FORMAT CELLS|PROTECTION. There you deactivate the option Locked. If you frequently change the protection of individual cells, you can add the

rules you thus worksheets. Figure ensure 9-1. the Two form dialog against sheets incorrect for datainput, validation and you Previewn give the user useful additional info

Excel tests in its calculation of the cells in which the IF formula is locatedIF

AND returns the Boolean value TRUE if all the listed conditions are satisfiedORTj/F5 1 Tf21.61

POINTER Of course, you can also define special formats for each of these four cases (number positive, negative, 0 text). A considereound]TJ-T*(inormatsioncan ab fournd in Ch

Color Colored text, and cells with a colored background, present problems when a document is printed. On the other hand, colors can make the use of a smart form much more user friendly. A way out of this dilemma is to carry out the printing with a macro designed to solve this problem. This macro (which can be easily recorded) eliminates from the printing all background colors and then restores the original format. If this restoration is computationally expensive, you can simply copy the entire worksheet to the clipboard, insert a new worksheet, and there insert the contents of the clipboard, eliminate the background colors, print the worksheet, and then delete it. In this way the original is left untouched. An example of this and then.7(d(,)o)2he sw v[(ana)0.1ft untout the

Templates Linked to Databases


Excel comes fitted out with a template wizard (command DATA|TEMPLATE WIZARD; if this item does not appear in your menu, you must activate this extension with the

Figure 9-4. Dialog for saving a new file based on a template

In principle, the new template is used as before: fill out, save, print. The only

Features of the Forms Design


In our smart form all the cells in which input values are allowed are colored yellow

In Speedy.xlt four names for individual cells were defined:


printrange: nrOfCopies: original_copy: invoiceNr: A1:I47 L19 B14 L17

When Speedy.xlt is closed, all changes are automatically saved. This applies particularly to the invoice number, which is increased by 1 each time an invoice is printed.
Private Sub Workbook_BeforeClose(Cancel As Boolean) ' does not ask whether the file may be overwritten Application.DisplayAlerts = False ThisWorkbook.SaveAs FileName:=Application.TemplatesPath + _ "Speedy", FileFormat:=xlTemplate Application.DisplayAlerts = True ThisWorkbook.Close End Sub

TIP With the SaveAs method in SaveTemplate the file is saved in the per-

Response to Errors

statusbarMode = Application.DisplayStatusBar Application.DisplayStatusBar = True Application.StatusBar = "print invoice ..." Set ws = Worksheets(1) ws.Unprotect ' print invoice ws.[original_copy] = "Original" ws.[printrange].PrintOut Preview:=True If Err = 0 Then ' print also n duplicates For i = 1 To ws.[nrOfCopies] ws.[original_copy] = "duplicate " & i Application.StatusBar = "print duplicate " & i ws.[printrange].PrintOut If Err Then Exit For Nshgti w' opy heetsinv a new wrksbook and sav

SOpplSOppluwoWcate_dplSOngBaFxTWoice ws.[original_copy[ws.[original"]TjrThr[ws.[printra ye ..."]TjrThTWnWbSet ws = Ww s.Adde ..." ySetTWnWb. ws = Worksheets(1)

wonly cells (values, f3T7r[wos), bxTWnorThTwiolsTWnal"]Tjr yThrA1Twanasteth&xuwoWal xlValuesTWnal"wo

For i =8TWes]pdthw jrTCells(1,Fo )alumnW[pdthFor]Tjr/T3/TfwWEb3T7r[Nshgti]TTWnWb. [p dowksheion.Dsws.

btnClear_Click ' save template SaveTemplate End If Application.ScreenUpdating = True End If If Err <> 0 Then MsgBox "An error has occurred" End If ws.Protect Application.StatusBar = False Application.DisplayStatusBar = statusbarMode End Sub

If the charges seem high, it should be borne in mind that they are conceived Afborthat short commarecfIt cofthe chaec-sartom amodel,leatuse esectutn]TJ-1.8947 -1.4211 TD-[

The button labeled PRINT INVOICE initiates printing of the form. The macro

The two input1 llroxr to idaily rate are D0.9and E26. In G0.9to idifference

The keyword For

time2 = 1 + endTime Else time2 = endTime End If For varTime = time1 To time2 - 1 / 1441 Step 1 / 24 nrOfHours = Int(varTime * 24) Mod 24 Rate_I_Hours = Rate_I_Hours + 1 End If Next varTime End Function 'convert to full hours If nrOfHours >= 8 And nrOfHours < 20 Then

The loop that now follows runs through the hours (one hour corresponds to 1/24 in Excels time format) from the start time to exactly one minute before the end time (1 minute corresponds to 1/1440; here 1/1441 is used to exclude possible round-off error). The number of the hour is calculated in the variable

Printing the Form


The last macro we wish to describe is btnPrint_Click. This macro prints out the

Data Series: A data series describes a related unit of data (usually the values of a column from the underlying table; only if you select Series in Rows in step 2 of the chart wizard will data series be organized by rows). For exam-

grid lines is determined by the tick marks on the coordinate axes. Theg47Wcha(mo1947 [(s

Error Indication
Data series in two-dimensional charts can be provided with error indicators (error bars). These are small lines that specify the range in which the actual value of a data point is to be found if statistical error of measurement is taken into account.

Printing
When it comes to printing a chart two variants must be considered: If the chart is embedded in a worksheet, then printing is accomplished by way of printing the worksheet. Here the only problem is that Excel does not give much thought to where page breaks are inserted, and even a small chart might find itself broken into four pieces. It does not hurt to check the page preview before printing. You may find yourself compelled to insert some hard page breaks to optimize printing (INSERT|PAGE

10.2 Programming Charts


First attempts at programming charts are often very difficult. The reason is that it

Figure 10-2. The most important objects of a chart

Chart

ChartArea: This is the background of the chart. With the properties of this object you can set color, borders, and so on. However, this object has a greater significance insofar as its methods Copy, Clear, ClearContents, and ClearFormats

Series, Point

With deleting chart data, too, you have to access the ChartArea object. Clear deletes all the chart data, ClearContents only the charts contents (here is meant primarily the data series), and ClearFormats only the formatting information. If you wish to insert an empty ChartObject into a worksheet (that is, an empty chart framework), you apply the

Ineporting of17oe data it is assumed17oat17oe dataseries A1, Ac576]sare

Figure 10-7. A page from the three-page monthly report

Program Code
Overview of the Components of Chart.xls
The Excel file Chart.xls consists of the following worksheets:
Intro:

The construction of the worksheets must not be altered, since access to particular cells is carried out directly in program code. The program code is divided into the following modules:
ThisWorkbook: FormDateInput: MenuEvents: CreateDateFiles: CreateReports: display menu on opening; delete it on closing. form for input of date range. event procedures for the menu commands. procedures for generating the test data. procedures for building and printing the daily and monthly

Next i Application.Calculation = xlAutomatic Application.DisplayAlerts = True On Error Resume Next ' delete existing file If Dir(filename)<>"" Then Kill filename wb.SaveAs filename wb.Close False If Err = 0 Then GenerateDailyWorksheet = True Else MsgBox "An error has occured: " & Error GenerateDailyWorksheet = False End If

The procedure opens the file with the daily data and copies some basic information (daily average and maximum) from it into the worksheet DailyReport. Furthermore, the title of the report is extended to include the relevant date. To generate a new chart, first three empty ChartObject frames are placed in the worksheet. Then ChartWizard is used to create charts within them corresponding for the most part to the actual requo0 corr-entso0 cor.on S somdet9(aens ates ar)19.7(notts w

chartWSheet.[DailyMax].PasteSpecial xlValues ' create three charts For i = 1 To 3 chartWSheet.ChartObjects.Add(30, 150 + 200 * (i - 1), 400, 185). _ Name = "Daily data " & i chartWSheet.ChartObjects("Daily data " & i).Activate If i = 1 Then ActiveChart.ChartWizard protWSheet.[A3:D99], _ xlLine, 4, xlColumns, 1, 1 ElseIf i = 2 Then ActiveChart.ChartWizard protWSheet.[A3:A99,E3:E99], _ xlLine, 4, xlColumns, 1, 1 ElseIf i = 3 Then ActiveChart.ChartWizard protWSheet.[A3:A99,F3:F99], _ xlLine, 4, xlColumns, 1, 1 End If Next i ' format charts For Each chobj In chartWSheet.ChartObjectsts

.PlotArea.Height = 140 .Legend.Left = 340 .Legend.Width = 50 .Legend.Border.LineStyle = xlNone End With Next chobj ActiveWindow.Visible = False protWBook.Close chartWSheet.PrintOut Preview:=True End Sub 'deactivate chart

Monthly Report
The monthly reports are somewhat more lavishly decked out than the daily reports, taking three pages in all. The first side consists of an ovets n the s of asiewo

Thep antg:dvforREMARKST scalingp The mot. ofp charts ep thar is yp eb thrX-axis nopep mor is uedpable.compr indetp o ofp heul ,thep bu carpiys numberp i as ofp changex daysp ther mon in ofp31pnp I days. thepcasepofpmonthspwerp ithf dayspThusp ther thepailbespcv

chartRange.Cells(i, 1) = z filename = ThisWorkbook.Path + "\d_" + _ Format(z, "yyyymmdd") & ".xls" If Dir(filename) = "" Then For j = 1 To 5 chartRange.Cells(i, 1 + j).FormulaR1C1 = "" chartRange.Cells(i, 7 + j).FormulaR1C1 = "" Next j Else filename = "='" & ThisWorkbook.Path + "\[d_" + _ Format(z, "yyyymmdd") & ".xls]Sheet1'" For j = 1 To 5 chartRange.Cells(i, 1 + j).FormulaR1C1 = _ filename & "!R19C" & 8 + j chartRange.Cells(i, 7 + j).FormulaR1C1 = _ filename & "!R21C" & 8 + j Next j End If Next i If nrdays < 31 Then For i = nrdays + 1 To 31 For j = 1 To 12 chartRange.Cells(i, j).ClearContents Next j Next i End If Application.Calculate chartWSheet.Range("B9:M39").Copy chartWSheet.Range("B9:M39").PasteSpecial Paste:=xlValues Application.CutCopyMode = False chartWSheet.PrintOut Preview:=True Application.Calculation = xlAutomatic End Sub

.lblInfo = "Date range for which monthly reports will be " & _ "created and printed." .Show

10.5 Drawing Objects (Shapes)


Overview

The Shapes enumeration enables access to all e

Figure 10-9. A star of colored arrows

POINTER

10.6 Diagrams

Beginning with Excel 2002 you can use INSERT|DIAGRAM to insert an organization chart or one of five additional types of diagram into an Excel worksheet (cycle diagram, rsiagprdiagrymiddiagr cenndiagrgat These]TJT*-[(iagr)9.57am,s iagr appearint a basic fotmatrand an u

Inserting Diagram Elements


A new diagram, regardless of type, is originally empty. The next step consists in filling the diagram with elements (with DiagramNode

C H APTER 11

Data Management in Excel


T

Occasionally, the database system will itself be -d a database (and not the data stord within it). This shorthand can rsult in considerable confusion. Of course, ther ar grat differnces among differnt database systems, rlating to the scope of the data to be managed, data security, efficincy over networks, and programming. In essnce ther ar two categories:

that are2522 -684inked by e2522 -6lations2522 -. This e2522 -6sults in a number of adv

Why Is Excel Nonetheless Used as a Database System?


Excel is simple to use. The learning curve with a new database program is steep. Excel is available. Another program would first have to be created. Excel has elementary database functions available and is therefore quite suitable for simple database applications. (The problem is just that over the course of time most small applications grow larger!)

When Should Databases Be Used Directly in Excel?


After so many critical observations you are probably at the point of uncertainty as

Creating a Database in Excel


The database concept in Excel is irresistibly simple: Any table or list can be interATA

An Employee Database
As an example database, the file Staff.xls is available to the staff of a firm, members of a club, or students and faculty of a school, or whatever. In the following paragraphs are presented some details of this minidatabase. In the first column the individuals gender (m/f) appears, and in the second,

Salutation = "Dear " & first_name & "," End If End If End Function

Input, Alteration, and Deletion of Data with the Database Form


In general, databases can be edited directly in the worksheet; that is, data can be

Sorting, Searching, and Filtering Data


Sorting Data
One of the most important database commands is DATA|SORT. This command leads to the dialog displayed in Figure 11-3. There you can input up to three columns of your database according to which you would like the data to be sorted. The input of several sort criteria can be useful, for example, for printing a multiple mailing in which you can save postage costs by sorting first by state and within state by ZIP code. The sort command sorts, as a rule, in the range in which the cell pointer is located. However, the command can also be used to sort cells that have been explicitly selected, independently of whether that particular range of cells is related to a database. In this connection the meaning of the two option buttons

columns instead of rows. A sort by column appears seldom in practice. In database applications it is difficult to imagine a situation in which such a sort would make sense. The sort command can be undone with an immediate appeal to EDIT|UNDO after it has been executed. Nonetheless, the command should be used with great care. It can destroy the construction of a carefully crafted table. Particularly critical is the sorting of tables whose formulas relate to cells outside of the data record or tables to whose cells reference is made in other formulas. Upon sorting, Excel changes all relative references that refer within the sorted range to cells outside of the data record. Depending on the construction of the table this can make sense, or it could spell disaster! After executing the sort command check the contents of the table. If the result does not correspond to your expectations, undo the sort command and alter the tables construction by replacing relative references with absolute references (a painful task that cannot be

(NonBlanks): (Custom): (Top 10):

Indicates data records whose field in the current column is not empty. Indicates those data records that correspond to the selected criterion in the dialog box (see Figure 11-3).

Indicates those records with the largest or smallest values. It does not tableeld in ords with the matcgterion necessarily have to be ten records. You can specify59.7(.6(TD-0.00a9erurr)y59.4444E

The decisive characteristic of advanced filters is that the filter criteria must be formulated in a specific range of cells. This range consists of a header row and one or more criterion rows. In the header row are entered all the column headers that are relevare09othe cserechcriterioa Thieheaders tust bmatchcexctelytheosein ahe ]TJT*[(adatab aust be . anlar5.6(a)29.87w iteria ,the seiaed]TJT*[0.0002 Tc0-.0001 Tw[(Tjoind awith)35.86wnr35.8

CAUTION As long as there is one cell in the search range that satisfied the search criterion, this will be found, even if this cell is above the parameter after. For this reason the following lines lead to an infinite loop if the search range contains a single cell that contains the character string xyz.

Displaying the Database Form

With Names.Add the name WinWordAddresses is defined. The cell range of the address list is determined with CurrentRegion and is transformed with Address into a character string of the form =DataForWinword!$A$1:$Q$5 with

FILTER

rng.AutoFilter ...

activate autofilterL

11.5 Consolidating Tables Fundamentals

By consolidating tables is meant that the data from several tables are collected into a single table. This process is most easily understood in the context of a concrete example: Let us suppose that you have four identically formatted Excel files with quarterly reports of certain sales figures, andouwish ntocuraeteouxt of thm as newd E xcel fil (with theannuals figur)19.7(es)19.6(.Or pcer)6(hapsd in thepur)19.7(vio uswE)576eek
ATA|CONSOLIDATE

is useful.

uswcell se9.6(angesnmust be specified. )35.8(These se9.6(angesnmay be locin the curr)19.7(int)]T allow u.DTh thepu5cchtocurint the8u5cchionl7(ocflexie tin se colidatm.2r or)5.7(ksheet,a, or)curryan(et,sof f7(epor)-m

Figure 11-12. Consolidation of measurement data

Consolidation via VBA Code


If your desires run in the direction of automating consolidation, then the macro recorder can assist you in achieving correct code quickly. For the example above it would look something like the following:
Selection.Consolidate Sources:=Array( _ "'I:\Code\XL-2000\[Consolidate.xls]sheet1'!R4C2:R20C4", _ "'I:\Code\XL-2000\[Consolidate.xls]sheet2'!R4C2:R20C4", _ "'I:\Code\XL-2000\[Consolidate.xls]sheet3'!R4C2:R20C4", _ "'I:\Code\XL-2000\[Consolidate.xls]sheet4'!R4C2:R20C4", _ "'I:\Code\XL-2000\[Consolidate.xls]sheet5'!R4C2:R20C4", _ "'I:\Code\XL-2000\[Consolidate.xls]sheet6'!R4C2:R20C4"), _ Function:=xlAverage, TopRow:=True, _ LeftColumn:=True, CreateLinks:=False

The method Consolidate is applied to a Range object, which may specify the size of the target range or simply a start cell for the operation ([B4] in the example

isoopendfotheosmartoformofamilroomo fr ChapteroRapearsoonotheomonitrotogehrowithoaocustomomenuoTseoeo igurF yy-yN6IoOther

With the VIEW menu you obtain access to other sheets of the application: VIEW|M

Managing Custom Menus

Initialize Invoice Form

accountCell.Cells(accountNr, 1) = accountNr accountCell.Cells(accountNr, 2) = accountWs.[invoicedate] accountCell.Cells(accountNr, 3) = Now accountCell.Cells(accountNr, 4) = accountWs.[membername] accountCell.Cells(accountNr, 5) = accountWs.[car] accountCell.Cells(accountNr, 6) = accountWs.[startTime] accountCell.Cells(accountNr, 7) = accountWs.[endTime] accountCell.Cells(accountNr, 8) = accountWs.[hoursI] accountCell.Cells(accountNr, 9) = accountWs.[hoursII] accountCell.Cells(accountNr, 10) = accountWs.[hoursIII] accountCell.Cells(accountNr, 11) = accountWs.[startDate] accountCell.Cells(accountNr, 12) = accountWs.[endDate] accountCell.Cells(accountNr, 13) = accountWs.[weekendbonus] accountCell.Cells(accountNr, 14) = accountWs.[nrOfMiles] accountCell.Cells(accountNr, 15) = accountWs.[fuelcost] accountCell.Cells(accountNr, 16) = accountWs.[invoicetotal] If monthReport.[A2] < accountNr Then monthReport.[A2] = accountNr monthReportWb.Save End Sub ' save changed file

Editing a Preexisting Invoice


The procedure ChangeOldEntry represents, in principle, the inverse function to SaveAccountData

C H APTER 12

Access to External Data


IN CHAPTER

12.1 Fundamental Concepts About Relational Databases

total price of the order

Figure 12-2. Data for an order are divided among four tables

Figure 12-3. Tables and relations of the Northwind example database

The database contains about eighty products in eight categories from thirty

If you have already set up a query with MS Query and saved it in a *.dqy file, you can use this query file as the starting point for a new query.69(tu9474 -2.3158-0.0-538.

Figure 12-5. Selecting the table fields

The following two dialogs make it possible to filter the data (for example with UnitPrice<10, to select only inexpensive products) and to sort them (for example, by product name). We shall not make use of these possibilities here. In the final dialog (Figure 12-6) you have three possibilities: You can return the selected data to Excel, you can view the data in MS Query and there process the

The first option makes sense only if your query (as in the current example) is so trivial that further refinement is unnecessary. In this case a further dialog appears, in which you specify where and how the data are to be placed in Excel (Figures 12.7 and 12.8). As a rule, you need to give only the start cell and click OK. (The numerous options are described somewhat further below.)

Figure 12-7. ent e3((tlset celling ar)19inve E

CAUTION Updating the data works only if the data source has not changed its location. For example, if the database file has been moved to another folder, Excel displays an error message when updating is attempted. The new location of the database file can be given in the login dialog that then appears. P

Figure 12-9. The program MS Query with the Orders table

Figure 12-10. A listing of all Northwind orders

Figure 12-11. Filter criterion for the orders

Figure 12-12. A listing of orders of the employee King

Figure 12-13. MS Query can execute calculations for each columnFigure 12-14. A listing of the total four additional calculational functions (minimum, maximum, average, and count). Basically, these functions come into play only when the list contains identical data recordswith the exception of the data field of the current column. In this case these data records are united into a single record, where the calculational function is then applied. However, it is impossible in MS Query to group and sum data

Sort and Filter Criteria


With the sort symbol (A_Z) you can sort the database according to the current column or selected columns. The command RECORDS|SORT allows sorting according to

More clearly formatted, the SQL code in Figure 12-15 looks as follows:
SELECT Employees.LastName, Sum(Quantity*UnitPrice) AS 'Sales' FROM 'D:\code\Xl-2000-engl\Nwind'.Employees Employees, 'D:\code\Xl-2000-engl\Nwind'.'Order Details' 'Order Details', 'D:\code\Xl-2000-engl\Nwind'.Orders Orders WHERE Employees.EmployeeID = Orders.EmployeeID AND 'Order Details'.OrderID = Orders.OrderID GROUP BY Employees.LastName ORDER BY Sum(Quantity*UnitPrice) DESC

Figure 12-15. SQL code for the query of Figure 12-14

POINTER A brief introduction to SQL can be found later in this chapter.

Queries Executed on Request


MS Query executes at once every change in a query, whether a new sort order or a new filter criterion. This is practical for experimentation with small databases, but

Options for Inserting External Data


Immediately before data resulting from a new query are imported into Excel, the dialog RETURNING EXTERNAL DATA TO MICROSOFT EXCEL appears. With its PROPERTIES button you can select a host of options (see Figure 12-16). These same options can be set after the fact with DATA|GET EXTERNAL DATA|DATA RANGE PROPERTIES.

Figure 12-16. External Data Range Properties

SNING

The option SAVE PASSWORD is useful only for queries that apaaa passworapon S

If you wish to edit QueryTable objects via program code, the usual modus operandi is first to create a query using MS Query and then use this character string as the starting point for your program code. A similar way of proceeding was also chosen to get around the greatest deficit

Syntax Summary
QUERYTABLE OBJECT

ws.QueryTables(n)

Introductory Example
As with all the examples of the section, the following procedure accesses the

ADO Overview
ADO OBJECT HIERARCHY

Connection Command

creates the connection to the database

Naturally, you must specify at some point the data source, and internally, in any case, a Connection

The keywords for the

SQL Abbreviations
As a rule, to open a

TIP Please note that most databases can place NULL in a field. This means that no data are available. This can lead to problems if you wish to allocate a particular type to the field of a variable, such as x$ = rec!comment. You must test with IsNull(rec!comment) whether the field contains any data at all.

Navigation in Data Records


Navigation within the list of data records is accomplished primarily with the help of five methods: MoveNext MovePrevious
activates the next record activates the previous record

To edit an existing data record, you need to change only one of the fields (thus rec!fieldname = newvalue). In contrast to the DAO library there is no longer an Edit method to introduce the editing p intr). .0(d, ys made aibr)966(asavor)as soonoexecuted.dutomac 11.3376 0 TD[thie c7sr arO liginal ldname TD= niting p oneThesrealsoebe deter-em

INNER JOIN joins two tables through a common field (for example, an ID number). INNER JOIN is of central importance in relational databases when data are to be combined from several tables. WHERE specifies the conditions that the fields must satisfy. If WHERE is not used, then the resulting Recordset contains all the data records of the table. GROUP BY field combines all the resulting rows for which the given data field

SELECT OrderID, SUM(UnitPrice * Quantity * (1-Discount)) AS Sales FROM [Order Details] GROUP BY OrderID Order ID 10248 10249 10250 10251 Sales 440 1863.4 1552.59998965263 654.059999750555

Editing Data

Thus instead of receiving a carton of fill-out questionnaires, y

Alternatives, Variants, Improvements


As with most problems, here there is not a single solution but many. To prevent my setting you, dear reader, loose with this one example without your considering some alternatives, the following list gives some suggestions as to alternatives, variants, and possible improvements. The example presented here uses MS Forms controls in the questionnaire. This requires at least Excel 9. If you would prefer to use the older controls (toolbar Forms), your Excel file will be backward compatible to Excel 5. If you would like to do without controls entirely, then you might be able to achieve compatibility with even older versions of Excel. Our example uses no VBA code in the questionnaire. (The controls are not linked to code.) The advantage of this modus operandi is, of course, that the macro virus warning is thereby avoided. On the other hand, with additional code you could construct a much more intelligent form, in which, for example, certain questions could be posed that depended on the answers to previous questions.

CAUTION The initial plan was simply to delete the sheets survey and listdata. But it turned out that wb.Worksheets(survey).Delete leaves the file in a damaged state. The file can be saved, but at the next attempt to open it, Excel crashes. For this reason this sheet is not deleted in its entirety, but only its contents (Cells.Clear for the cells, Shapes().Delete for the controls).

The insertion of a new data record into the surveydata table of the database is simply accomplished with AddNew. Then the result cells of the worksheet results are read and saved in various fields of the data record. Finally, the method Update 1 Tw[(arCsw r)19.4(ecor)19.4(d.w r)1 s!!-./$h

!profession = ws.[b3] !pubaw = -CInt(ws.[b4]) 'False>0, True>1 !pubapress = -CInt(ws.[b5]) !pubgalileo = -CInt(ws.[b6]) !pubidg = -CInt(ws.[b7]) !pubmut = -CInt(ws.[b8]) !pubmitp = -CInt(ws.[b9]) !puboreilly = -CInt(ws.[b10]) !pubquesams = -CInt(ws.[b11]) !pubsybex = -CInt(ws.[b12]) !internet = ws.[b13] If ws.[b14] <> 0 And ws.[b14] <> "" Then !Comments = [b14] End If .Update End With ' close file and move it into archive directory wb.Save ' Stop wb.Close ' new filename: ' ' directory incoming instead of archive yyyymmdd-hhmmss-oldname.xls instead of oldname.xls "incoming", "archive", compare:=vbTextCompare) newfilename = Replace(newfilename, _ fil.Name, Format(Now, "yyyymmdd-hhmmss-") + fil.Name) fso.MoveFile fil, newfilename End Sub

newfilename = Replace(fil.Path, _

It is worth mentioning the use of the function

The Auxiliary Function OpenSurveyDatabase

Figure 12-26. Testing an SQL query in Access

TIP

' publishers publ = Array("pubaw", "pubapress", "pubgalileo", "pubidg", _ "pubmut", "pubmitp", "puboreilly", "pubquesams", "pubsybex") For Each p Ingalile"YFw + 1p In2sXrec.Open "SELECT COUNT(id) AS ", "puult FROM "puurveydata "

Generating Test Files for the incoming Directory

13.1 Grouping Data (Subtotals)

The largest permissible value for ShowLevels

Figure 13-3. A database with two pivot tables

Pivot tables are created with the command DATA|PIVOTTABLE AND PIVOTCHART REPORT. This command summons the PivotTable wizard. The goal of this example (that is, pivot table 1 in Figure 13-3) is to determine for each product category and quality level the number of articles and their mean value. To accomplish this the following steps were executed: Step 1

Step 4: Now it is time to move, with the mouse, data fields (column headers from the initial data) from the pivot table toolbar to their proper place in the table. See Figures 13.4 and 13.5. The two ranges RowField and ColumnField define the groups into which the table is to be divided. The range DataField specifies what information is to be displayed in the individual groups.

Step 6:Because averages are being computed, a number of decimal places are displayed, too many of which make the table unreadable. Therefore, open FIELDSETTINGSonce again, cl CELLS, the new format holds not just

TIP When a pivot table contains several data fields, you can remove all of

CAUTIONExcel

cannot

change

pivot

table

to

accommodate

fundamenta

For the last four named settings a second data field must be specified in relation to which the calculation is to proceed.

CAUTION The problem mentioned in the last chapter in connection with MS Query, that the names of Access databases are stored with the absolute pathname (with drive and directory), affects pivot tables as well. When both the Excel file and Access database file are moved into another directory, Excel no longer can find the source data and therefore cannot update the pivot table. A way out of this dilemma is presented later in this chapter.

REMARKS There are two principal ways of dealing with pivot tables with external data: The first consists in importing as much data as possible and then ordering it with the means available to pivot tables. This gives you maximal freedom in constructing the pivot table, but also requires a large amount of memory for storage. The other option is to attempt at the time of importation of the data to attempt to reduce this to a minimum. (This, then, costs more time in managing the often unwieldy MS Query.) The advantage is that the system requirements in Excel (processor demand, storage) are considerably less, and the processing speed correspondingly greater.

OLAP Cube Files


OLAP stands for Online Analytical Processing

Fe 13-15. Development of a complex query with MS Queryy o

Now either you can specify in the last step of the query wizard that you wish to create an OLAP cube from this query, or you may execute in MS Query the command FILE|CREATE OLAP CUBE

Pivot Table Options


If you execute the command TABLE OPTIONS in the pivot table toolbar, the dialog

To generate a new pivot chart execute the command DATA|PIVOTTABLE AND PIVOTC

Construction and Reconstruction of Existing Pivot Tables


Rang

' Pivot.xls, Code2 Private Sub btnCreatePivot1_Click

Figure 13-25. Analysis of the PivotCache object in the Watches wi

According to the data source, various properties of the object are employed. An attempt to access other properties leads to an error message. For some strange reason there is no property that is always available and that specifies the type of the data source. Thus if you execute a loop over all PivotCache

EXTERNAL DATA SOURCE (VIA MS QUERY)

QueryType CommandType Connection

contains xlODBCQuery contains xlCmdSql contains connection information as with a QueryTable object (ODBC;)containsagtaisthe SQL; ho evuer it is brQ

. One mustmustc(,)t7efoubeF

14.1 Add-Ins

Excel comes equipped with a host of so-called add-in files. These files are located in the directory OfficDirectory\Office\Library and have the task of extending the functionality of Excel at a number of points. They can be activated and deactivated with the add-in manager. Since loading an add-in function requires a certain amount of memory, you should activate only those add-ins that you truly need. Add-in files can be recognized by the suffix *.xla. In addition to the add-in files suppli[(I)17.8ee,ditioxFe suf/F22 1 Tf/F22 416.3216 530115.2 6

Applications of Custom Add-Ins

' AddInFn.xls, Module1 Function AITest(x As Double) As Double AITest = 2 * InternalFunction(x) Private unction

There are two ways of solving this problem. The first variant consist in separating the application into two files. One file contains code, menus, and forms and is

14.2 Excel and the Internet Sending Excel Files as E-Mail


With the method SendMail of the

HTML Import
POINTER The importation of text (Chapter 5), databases (Chapter 12), and

tation, I Ecel attempts, depend1g onsett1gs of

Developing Your Own Smart Tags

Using a Simple Web Service in Excel


To try out communication with a web service, you must either create such a service yourself (for example, with Visual Studio .NET) and make it available on a local

Example Program
The event procedure for the button in our example program is a bit more complex. Two reasons for this are that the procedure has been protected against possible errors and that during the (usually quite slow) communication with the web service the amount of data transmitted is displayed in the status bar. The actual code be_TJ1 T()]T,itializunicatuntT()]

The Parameter List of the DLL Declaration


You must supply the data types of the parameters of the DLL function and the type of parameter passing in the parameter list. Many difficulties arise from the differing data types between d5obBA and the programming language C, for which the DLL functions are usually conceived.

given par esses to the DLL function. If the r eLL

Function NullString(x) NullString = Left(x, InStr(x, Chr(0)) - 1) End Function ' DLL.xls, Tabelle1 Private Sub btnShowWindowsDir_Click() MsgBox "The path of the Windows directory is " & WinDir() End Sub

TIP The above example is of a strictly pedagogical nature. The Windows

The Limits of Excel

You create an object with CreateObject. As parameter you must specify the object class that identifies the program. The following lines create the connection to Word. Dim word As Object Set word = CreateObject(Word.Document.8) The character string Word.Document.8 identifies the object that you wish to

F.i2.1(igur)25.8(e 14-8.)-207.6(The first page of the r)25.7(epor)-7.9(t printed b)5.7(y)0.2( A)5.7(cce

Static acc As Access.Application report_anothertry: fil$ = ThisWorkbook.Path + "\nwind.mdb" ' start Access, load database If acc Is Nothing Then Set acc = GetObject(fil, "access.project") End If On Error Resume Next ' error if no CurrentProject prjName = acc.CurrentProject.Name On Error GoTo report_error If LCase(prjName) <> "nwind.mdb" Then acc.OpenCurrentDatabase fil, False End If

Example: Displaying HTML Files (Internet Explorer)

obj.Toolbar = 1 obj.Visible = True End Sub ' terminate Explorer

'activate toolbar 'display Internet Explorer

Private Sub CommandButton2_Click() On Error Resume Next If Not obj Is Nothing Then obj.Quit Set obj = Nothing End If End Sub

Excel as Server (Control by an External Program)


Up to now we have proceeded fro s0 9.5 1 1 Tfumptionatd frgr

If win.Parent.Title = "ActiveX_Chart_keyword" Then ' we have found it! Set wb = win.Parent Exit For End If Next End With ' If an error has occurred, Excel is ' perhaps no longer available If Err <> 0 Then MsgBox "An error has occurred. " _ & "The program will be terminated. To" _ & "execute this example program Excel 2000 must be installed" _ Unload Me End If PlotChart Me.OLE1.Visible = True MousePointer = 0 formWait.Hide End Sub

Drawing a Chart
Drawing the chart takes place in a separate procedure. The idea is simple: In two

Sub PlotChart() Dim xfreq, yfreq Dim x#, y#, z#, data$ xfreq = formPara.SliderX yfreq = formPara.SliderY ' calculate new data For y = 0 To 2.00001 Step 0.1 For x = 0 To 2.00001 Step 0.1 z = Sin(x * xfreq / 10) + Sin(y * yfreq / 10) data = data & DecimalPoint(Str(z)) & vbTab Next x data = data & vbCr Next y Clipboard.Clear Clipboard.SetText data wb.Sheets("table").Paste wb.Sheets("table").Cells(2, 2) ' so that the chart and not the table is displayed wb.Sheets("chart").Activate ' Activate alone does not help, for whatever wb.Sheets("table").Visible = False End Sub ' replace comma by decimal point Private Function DecimalPoint$(x$) DecimalPoint = Replace(x, ",", ".") End Function

TIP In transferring data via the clipboard a period must be given as the decimal point, even if one is using an international version of Excel in which

The remaining code of the program has little to do with Excel and is therefore not of interest to us. If you have Visual Basic, you can look at the remaining procedures yourself. If you do not have access to Visual Basic, you can examine the four *.frm files in the directory Vb6\Chart

and is not directly returned.) If the clipboard contains text, this is read with GetText and displayed via MsgBox. If a text is too long, MsgBox will truncate it.
Sub test2()

End Sub ' Method GetFormat: tests whether the clipboard ' has data in the given format Function GetFormat(format) On Error Resume Next GetFormat = ClipBoard.GetFormat(format) End Function

default command can have a different effect. Additionally, many OLE programs

.Height = 50 .Activate End With Sheets(1).[a1].Activate End Sub 'edit OLE object

Embedding an OLE Object Based on a File To embed a new object whose contents are prescribed by a file of the OLE progr and inke L

Creating a Connection to the Program

Figure 14-12. ActiveX Automation for a VB.NET program

' \vb.net\module1.Visual Basic ' to use late binding Option Strict Off Sub Main() ' process Excel file process_xl_file() ' close Excel

VBA Programming for Pros

If Shell is used as a function, it returns the ID number of the program. It is under this ID number that Windows runs the program internally. The number can be used to reactivate the program at a later time with AppActivate. The following instruction starts the Notepad program.
ID = Shell("notepad", 2)

Note, please, that VBA continues its work on the procedure after a short hesitation. Excel and the newly started program now run quasi-simultaneously and independently of one another. There is no way to determine within VBA whether a program is running yet or continues to run. (You would have to employ various DLL system functions that determine information about all running processes. This requires some rather difficult programming that would go outside the subject matter of this book. Details can be found in the KB article Q129796 in the MSDN library.)

Activating a Running Program


The command AppActivate activates an already loaded program. The command is passed as parameter the ID number of an earlier Shell command or the name of the window of the program to be activated. VBA is relatively forgiving in the way it interprets these parameters: Case plays no role. The program is activated as soon as it can be uniquely identified. AppActivate activates the program, but does not change its state. If the program is currently showing itself as an icon, then it remains an icon. Attempts to shift the program into another state with SendKeys (say, with Alt+spacebar, Ctrl+W) fails because Excel assumes that the key combination is meant for it (because after AppActivate it takes a while until the program is truly activated). If AppActivate cannot find the specified program, then error 5 occurs (invalid procedure call).

787

Part Four

C H APTER 15

Object Reference
THE BIGGEST PROBLEM in working with VBA is the enormous number of keywords. This reference chapter makes no attempt to list or describe the more than one thousand keywords. (One thousand keywords at two paragraphs each equals about five hundred pages!) That is the task of the on-line help, which despite its manifest insufficiencies is much preferable to a printed text. This chapter gives, rather, an overview of about two hundred objects that

15.1 Object Hierarchy


This section contains several hierarchical lists, in which the logical relationship among VBA objects is represented. These lists are restricted to various segments of the object hierarchy. Do not expect completeness! Alas, this book is too small to contain a complete hierarchical listing of all objects, because the object list contains countless ramifications, which in part lead to a common object, then branch off again, and so on, and so on. A complete object hierarchy would be much too long to satisfy any reasonable requirement of clarity. In connection with the object hierarchy the concepts of above and

Worksheet
Worksheet ChartObjects

embedded181 Tc457(o)

Range

anchor cells (via

Control of the Development Environment (VBIDE Library)


VBE

File Access with File System Objects (Scripting Library)


FileSystemObjects

With almost all enumeration objects of the Excel library, the first object is addressed with enumeration(1) (for example,

In the upper right corner of the syntax box appears the library from which the

The range of cells can be determined from the Range property, the name of the range from the Title property. The password cannot be immediately read out, but it can be changed with the method ChangePassword. Optionally, with Users.Add one can specify users who are permitted to change the range of cells without a password. AllowEditRanges Protection.AllowEditRanges Excel 2002

Areas Range.Areas (index)

Excel Range

If a cell range is made up of several partial ranges, then the object Areas refers to the rectangular partial areas of this range. Whether a composite range is at hand Range(index) pr

Axes Chart.Axes (type, group)

Excel Axis

The enumeration object Axes refers to the coordinate axes of a chart (see Axis). Identification comes from the input of the type (xlCategory for the X-axis, xlValue for the Y-axis, and xlSeries for the third axis in the case of a 3-D chart). For 2-D charts with two Y

Binder

PivotTable.CalculatedFields

CalculatedFields (name or index)

Excel PivotField

This enumeration object refers to those pivot fields of a pivot table that do not

Application.FindFormat Application.ReplaceFormat

Excel 2002 .Font Font This object describes the cell format that is used in finding and r

CellFormat

ChartArea Chart.ChartArea

Excel .Interior Interior .Border Border

The object ChartArea describes the visual appearance of the entire chart (includ-

ColorFormat FillFormat

Excel

CommandText. Then the values of the parameters are set. Finally, the command can be executed with the method Execute. If the command deals with a query, then Execute returns a Recordset object. CommandBar .Controls Office CommandBarControls

Application.CommandBars(..)

This object describes a menu bar or toolbar. More precisely, there are three types (property Type): normal toolbars (msoBarTypeNormal), regular menu bars (msoBarTypeM(),42156 -12.2(arT)TJ/F5 1 Tf8.6(y90 TD-0.0001 Tc[(), r)d depop-upenu b()]T/F8 1 Tf1

CommandBar.Controls

CommandBarControls (index or name)

Office CommandBarControl

Comment Range.Comment Range.AddComment(..)

Excel .Next/.Previous Comment .Shape Shape

This object stores the content and other information as notes (also called comments since Excel 97). With the method Text the comment can be read and edited. The methods Previous and Next refer to additional comments in the worksheet.

CustomProperty/CustomProperties Worksheet.CustomProperties

Excel 2002

DocumentProperties Workbook.

Office

Dim c As Range Set c = [a2] If c.Errors(xlEmptyCellReferences).Value = True Then MsgBox "formula refers to empty cells" End If If c.Errors(xlInconsistentFormula).Value = True Then MsgBox "formula is inconsistent" End If

File Files()

Scripting .Drive Drive ties ar he Ovf(ilsS naml),) at

FileDialogSelectedItems

Filters AutoFilter.Filters (index or name)

Excel Filter

This enumeration object refers to all filters of an autofilter (one for each column of the database). Floor Chart.Floor Excel .Interior Interior .Border Border

Floor

FormatCondition Range.FormatConditions(..)

Excel .Borders(..) Border .Font Font .Interior Interior

The formatting of a cell or range of cells can be made dependent on at most three conditions (FORMAT|CONDITIONAL FORMATTING). In this way.0974examplee

Gridlines

Excel

Label

MS-Forms

You must delete the entire legend with False and with

Mailer Workbook.Mailer

Excel

E anss0 -18(ver)f 39.7(kman2gement)9f m2-0.9tgemdisalogs294 6(. Eachdisalog shet .isTc(0)11.-

to

the

OLE

program

and

enables

how

the

object

is

attached

toExcel:

Pages MultiPage

MS-Forms

Picture

Excel 2002

PivotCaches Workbook.PivotCaches (index or name)

Excel PivotCache

This enumeration object refers to the Pivefers eotCachesExRange.6(aches)]TJ/3.1892[vo

PivotFormula

Excel

directly via PivotLayout. Chart.PivotLayout.PivotFields is a shorthand notation for Chart.PivotLayout.PivotTable.PivotFields. If a chart is not linked to a pivot table

Point Series.Points(..) .Border

Excel Border

PublishObject Chart/Range

Excel

Range Worksheet.Range(..) Worksheet.Cells(..) Application.ActiveCell Application.Selection onte

Excel .Cells Range .Areas Range .Font Font .Border Border

Scenario Worksheet.Scenarios(..) .ChangigCell .ChangingCell

Excel Range

ShadowFormat Shape/ShapeRange.ShadowFormat This object describes the shadow effects of C

.ForeColor o

Excel ColorFormat l o

SmartTagActions SmartTag.SmartTagActions

Excel 2002

Object Reference

smart tag. Add must be passed the type name of the smart tag. Add can be used only on Range objects when these encompass exactly a single cell otherwise, an error occurs.
ActiveCell.SmartTags.Add( _ "urn:schemas-microsoft-com:office:smarttags#stockticker")

SoundNote Range.SoundNote

Excel

With the SoundNote object sounds or sequences of notes can be associated with a table cell. The linking of sound information is accomplished with the methods Play

853

TickLabels Axis.TickLabels .Font

Excel Font

This object describes how the tick marks on a coordinate axis of a chart are to be labeled. Characteristic properties and methods are Orientation, Font, NumberFormat, NumberFormatLinked (True if the number format should be taken from the table). This object has influence neither on the location and content of the label nor on the number of label points. These details are handled by Axis properties, in particular, by TickLabelSpacing and -Position as well as by TickMarkSpacing (for X-axes) or MajorUnit (for Y-axes). ToggleButton UserForm.Controls .Picture MS-Forms StdPicture

The toggle button is a variant of an ordinary button. The special feature is that the toggle button does not spring back automatically after being pressed,gle c[.9.T*F8 presscl.C-0.00

The visual display of a curve is handled with the subobjects DataLabel and Border. DisplayEquation and DisplayRSquared

UserAccessList AllowEditRange.Users

Excel 2002

VBE Application.VBE

VBE .CodePanes(..) CodePane .CommandBars(..) CommandBars .VBProjects(..) VBProject .Com15.[(VBP)0 TD-0Lo/

Watch Application.Watches(n) Watches.Add

Excel 2002 .Source Range

The

Workbooks Application.Workbooks (index or name)

Excel Workbook

Workbooks contains the list of all loaded workbooks (including those that are invisible because their windows are hidden). Reference to individual workbooks can be effected either by the input of the index number or the file names (without path). With Add a new, empty, workbook can be declared. Open loads an existing workbook. Worksheet Workbook.Worksheets Application.ActiveSheet Excel .Range Range .Cells Range .XxxObjects XxxObject

Worksheets belong together with dialog, chart, and module sheets to the sheets of a workbook. Countless methods and properties refer on the one hand to ranges of cells (Range, Rows, Columns, Cells) and on the other to embedded controls, drawing objects, charts, pivot tables, and so on. The exchange , 3.9309.7(d)]TJ/F5 c of data via the1clipboard Tf,0403 0 is TD-0.2pli43c(, accompliand)17-Sour-0.0001eD-0.0001 3[(.)vot tTj/.1 TD[(a we2fhan321 Tc[(3.9771 Tf0.

A PPENDIX

Excel 2003 Beta 2


A

Visual Studio Tools forATA Office 6(wisuchn is not seen list as an integr (suchnhats)9ficwi08

at

tdisplayent

(respectively beneath) the list are automatically moveu e000.ieGhe liway to make(room forhe lie

If this condition is not satisfied, you can achieve better import results by influencing the importation process manually: You should specify which individual

Simple XML importation: To import f(0 73co)7p.x a paoricular place in a wpor5.7(k-:)]TJ-12.014

Excel generates a list into which all the data are to be imported. For the individual columns of this list (ListColumn objects) the XPath object is initialized. This determines which XML-element data are to be imported. Finally, the actual importation is carried out.Xich p8l tlementne.1.dd8ted

TIP If you are analyzing an existing worksheet and wish to locate all cells and ranges of cells that are linked to XML data sources, you can use the method XmlDataQuery or XmlMapQuery. These methods return the Range XPath objects are initialized according to search .

The goal is that location is to b imported ino bcell B2,

A few notes on the code: XmlMaps.Add actually expects a *.xsd file with the definition of the schema for the XML data. If a schema definition is unavailable,

Dim xmlfile As String Dim xmlstring As String xmlfile = ThisWorkbook.Path + "\testout.xml" xm.Export xmlfile xm.ExportXml xmlstring MsgBox xmlstring 'export into a local file 'export into the variable xmlstring

XML Form: In Chapter 9 I have presented several possibilities for using Excel for

ListColumns(..)

ListColumn .DataFormat

Excel 2003 ListDataFormat .Range Range xPa3hmn

Excel 2003 Beta 2

ListObjects WorksheetE

Excel 2003

875

Appendix

876

Index
Symbols
# symbol, 197 #If instructions, 75

881

altering data, with Database form, 57980 AltStartupPath property, 284 ampersand (&), 35, 177, 238 AnalyseCommandBars procedure, 47677 Analysis\Atpvbaen.xla file, 132 AnalyzeDatabase procedure, 679, 683

changes, undoing, 80 changing active workbook, 146 cells, 147 drives, 271 folders, 271

equipping classes with proper8 reW n2es,(16162)Tj-re1.1111 TD1 Tc0 3w[(ec0 2wippinxample fo

CommandBarControls object accessing, 468 BeginGroup property, 484 BuiltIn property, 484 Copy method, 48687 Id values of, 474 methods and properties, 815, 816od, 48687

C o a c c e s s i n g , 4 6 8 a c c e s s i n g , 4 6 8 o n t r , 4 8 C o a c c e s s i n g , 4 6 8 a c c e s s i n g , 4 6 8 o n t r , 4 8 C o o n t r e n t i n d i c a t o r o n l y o p t i o n J 1 0 3 2

advantages, 43839 communication between, 443 disadvantages, 439 formatting, 441 positioning, 442 program code for, 445 working with, 43941 Controls object, 818 Controls property, 467 Controls.Add method, 469, 471 ControlSource property, 407 ControTipText property, 407 ConvertFormula function, 616 ConvertFormula method, 192 ConvertNumberIntoEuro procedure, 35354 coordinate axes, 52, 531 Copy method, 2031Copy

navigation in, 659 searching and locally sorting, 660

dates and tim (continued) VBA functions, 25053 worksheet functions, 25354 year 2000, 24647 DateSerial function, 248, 250, 265 DateValue function, 250, 265 DATEVALUE worksheet function, 253, 266 DAVERAGE function, 596 Day function, 250, 253, 265, 266 dayCounter function, 259 days, 255 Days360 function, 251 DAYS360 worksheet function, 253, 266 DB_Cars file, J2 -111c_FC,5972 -111c_eS ,602(,603(,6072 -111c_C)11.8(ars)19.6.xlrs file)19.6(,451)]TJT*-0.00 956(,674(,675(,6795)]TJT*0.0003 Tw[dbsuer)180.2ve(y949.6.)-03(mdb file)1946(,6706)]TJT*-0.0002 Tc0.0001 Tw[(Cy)5 Ask Again Lanterbuttion,376 ,796 OKrbuttion,376 D.6lbug object(,766)]TJ-1.3333 -1.1111 TD[(methodes andpe-71.9t oie)9.7(,5482)]TJT*-0.0002 Tc0.0001 T

simulating keyboard input in, 38990 standard Excel, 38893 warning messages, 392 Dialogs object, 822 DialogSheets method, 219 Dialogs(xlDialogFormulaFind).Show, 23 Dictionary object, 166, 822 Dim command, 86, 88, 89, 92, 109 Dim field1(5), field2(10,10), 96 Dim var keyword, 112 Dimfield( ) field, 96 Dimfield(-3 through 3) field, 96 Dimx data field, 96 Dir command, 304 [Direct]Dependents method, 191 [Direct]Precedents method, 191 directories. See folders directory tree, 275 Discount function, 3067 Display An1.32250 TwoFc6T[ ) field, 96

embedded formulas, in smart forms, 496 employee database example, 57778 Employees table, 621 Empty value, 89

Excel 5 auto procedures in, 143 compatibility problems with Excel 7, 6264 events in, 14243, 158 worksheet functions, 232 Excel 7, 232 auto procedures in, 143 compatibility problems with Excel 5, 6264 events in, 14243, 158 new features, 59 Excel 97

setting tab order.[, 4034-1.1111 TDtting tab ovisual appearols settiusab

oAols

functions

links, between differing data types, 90 ListBox object, 833 listboxes accessing elements, 41314 controlling with events, 417 creating, 470, 47980 deactivated fields in, 699 events, 419 example, 41718 hierarchical, 856 linking range of cells to, 64 methods, 419

Minute function, 250, 266 MINUTE worksheet function, 253, 266 MkDir command, 304 Mod operator, 175, 177 mode parameter, 276 Mode property, 651, 666 modifying. See changing module sheets, 55, 219 moduleMenu event procedure, 614 modules, 7680.

Office documents, 59 Office Library, 49, 59, 801 Offset method, 37, 187, 189, 191, 660 Offset(row, column) method, 37 OK button, deactivating, 37 OLAP (Online Analytical Processing) cube files, 628, 7047 Olap.cub file name, 722 olap-cube worksheet, 710 OLE (Object Linking and Embedding) in ActiveX automation, 76163, 76970 fundamentalents

Print # command, 280 Print command, 240, 278, 299, 305 Print in black and white option, 534 Print method, 76, 81, 107, 299, 376, 386, 820 Print_Info procedure, 168 PrintAndSave procedure, 614, 615 Printed chart size option, 534 printing charts, 534, 54344 files, 145 invoice, in balance sheet example, 603, 61415

Protection object, 49, 843

RecordCount record, 660 RecordCount, Recordset property, 667 recording macros, 1112, 16, 8283 records. See data records Records|Automatic Query command, 637 Records|Query Now command, 637 Records|Sort command, 636 Recordset methods, 667

SheetBeforeRightClick event, 146, 156, 157 SheetCalculate event, 147, 156, 157 SheetChange event, 156, 157 SheetCombo_OnAction event procedure, 482 SheetDeactivate event, 156, 157 sheets, 21921 changing, 14546 deleting, 224 important properties of, 221

special functions, 235 SpecialCells method, 191, 203 SpecialCells property, 260 SpecialCells(xlVisible) method, 229, 592 Speech p112w[(S)24(pecialC)11.8(e)0litR object T keywofy

VBA (continued) history of, 67 special features of, 78 VBComponent object, 153

Web tables, 73940 WebOptions object, 744, 860 WebQuery (Import) object, 53 WeekDay function, 251, 265 WEEKDAY worksheet function, 253, 266 WeekdayName function, 252, 266

You might also like