Defiitive Guide To Excel Training
Defiitive Guide To Excel Training
Defiitive Guide To Excel Training
Definitive Guide to Excel VBA, Second Edition Copyright 2003 by Michael Kofler
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
Preface
EXCEL OFFERS RIGHT OUT OF THE BOX an enormous variety of functions. So why does
Part One
An Intuitive Approach
C HAPTER 1
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
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)
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
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
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 (
Chapter 1
C HAPTER 2
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
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
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
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
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
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
Alt+F11 Ctrl+Tab
C HAPTER 4
VBA Concepts
THIS CHAPTER DESCRIBES
NOTE
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
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))
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,
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
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-
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 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
Syntax Summary
Below, square brackets enclose optional commands, which may be given but do not have to be.
DEFINITION OF PROCEDURE
commands
Next var
LOOPS WITH FOR EACH NEXT
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
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
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
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.
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 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
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
Private Sub
End Property
The values of these constants correspond to the powers of 2 (20, 21, 22, 23,
C HAPTER 5
Techniques of Programming
T8 506.6429 Tm(T)Tj7.12 27F1 3 398/5ers
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
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
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.
clear content of cells clear formatting of cells clear content and formatting clear notes
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
' 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
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
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.
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
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
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-
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
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-
top of the object hierarchy listing of drives and partitions Drive object for describing the drive
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
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
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
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
TIP There are many other formats for saving a file or worksheet, such as HTML document, Unicode file, or database (dBase format).
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.
In the program
IMPORT / EXPORT
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
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
which are passed as binary DLL. But they have many other drawbacks. In particu-
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
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
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
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
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
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
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
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
Program Interrupts
The above example begins and ends with several lines that ensure the orderly ter-mination of th
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
SPEED OPTIMIZATION
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
' 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
The ADD WATCH form is particularly attractive if you wish to examine the prop-
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
If result = vbYes Then Resume Next End If ' otherwise, interrupt procedure ' ' .. cleanup tasks End Sub
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
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
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
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.
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
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
0 if the entire contents are selected upon activation True if upon Return a new line can be input
number of lines
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 selected text to the clipboard cut selected text to the clipboard
text box contents have changed a key was pressed keyboard input a key was released
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
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
METHODS
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
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-
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
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")
REFEDIT
PROPERTIES
Value
REFEDIT
Change
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[(
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
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
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.
With Controls.Add
Programming Techniques
CommandBarControl
' new entry in tools menu Set cbb = Application.CommandBars("Worksheet Menu Bar"). _ Controls("Tools").Controls.Add() cbb.Caption = "A new command" cbb.BeginGroup = True
movable listboxes (which then themselves form a toolbar; see the command C
COMMANDBARCONTROLS
Add Count
COMMANDBARCONTROL
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.
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
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
In principle, the new template is used as before: fill out, save, print. The only
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
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
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
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
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
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
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
C H APTER 11
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
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
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
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.
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
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
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
With the VIEW menu you obtain access to other sheets of the application: VIEW|M
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
C H APTER 12
Figure 12-2. Data for an order are divided among four tables
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.
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.)
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-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
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
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
Naturally, you must specify at some point the data source, and internally, in any case, a Connection
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.
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
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, _
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 "
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.
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
To generate a new pivot chart execute the command DATA|PIVOTTABLE AND PIVOTC
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
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
' 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
HTML Import
POINTER The importation of text (Chapter 5), databases (Chapter 12), and
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()]
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
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
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
Private Sub CommandButton2_Click() On Error Resume Next If Not obj Is Nothing Then obj.Quit Set obj = Nothing End If End Sub
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
' \vb.net\module1.Visual Basic ' to use late binding Option Strict Off Sub Main() ' process Excel file process_xl_file() ' close Excel
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.)
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
Worksheet
Worksheet ChartObjects
embedded181 Tc457(o)
Range
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
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
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
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
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
Office CommandBarControl
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()
FileDialogSelectedItems
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(..)
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
to
the
OLE
program
and
enables
how
the
object
is
attached
toExcel:
Pages MultiPage
MS-Forms
Picture
Excel 2002
Excel PivotCache
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
Excel Border
PublishObject Chart/Range
Excel
Excel Range
.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
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
The
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
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
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 .
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
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
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
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
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